Tag Archives: json

Check your JSON with JSONLint Software & Sites 16 JAN 2019

Seven years later and I still find myself using JSONLint whenever I need to check that a script is indeed producing or being supplied with a valid JSON string.

Pleasingly, a lot of my original 2012 post still checks out: “JSON, or JavaScript Object Notation, is a lightweight text-based open standard designed for human-readable data interchange. It is derived from the JavaScript scripting language for representing simple data structures and associative arrays, called objects. Despite its relationship to JavaScript, it is language-independent, with parsers available for many languages.”

In other words, a good option to shuttle a whole lot of key/value data between AJAX web services. The JSONLint tool itself validates JSON text, and also acts as a reformatter, making it much easier to debug a big chunk of JSON text.

Using the online JSON validator is as simple as copying your JSON text string into the big text area and hitting the “Validate JSON” button.

Useful little tool indeed.

Related Link: JSONLint

PHP: Simple method to get data from a JSON Web Service CodeUnit 12 NOV 2012

A lot of web services provide you with some useful JSON formatted data in exchange for a few parameters or just some love, and this is a particularly simple and easy method to grab some of that JSON goodness for use in your own PHP page.

In order to grab the data, we’ll first create a HTTP stream content where we’ll add the all important X-Request-With = XMLHttpRequest header that is used to identify requests as being AJAX requests. At this point you can add any parameters you wish to hit the web service with by adding them as an associative array and wrapping them in a http_build_query() call for the context content.

The next step is to use the classic file_get_contents (this assumes your apache/PHP allows the use of the function to open URLs) to hit the target URL using the newly created context.

This should work, resulting in a JSON object which you can use PHP’s json_decode function to manipulate.

In action:

$opts = array('http' =>
    array(
        'method' => 'POST',
        'header' => "Content-type: application/x-www-form-urlencoded\r\nX-Requested-With: XMLHttpRequest\r\n",
        'content' => http_build_query(array())
        )
    );
$context = stream_context_create($opts);
$result = file_get_contents("http://webservice.org/route/list/key/mykey/format/json", false, $context);
$jsondata = json_decode($result, true);

Nifty.

PHP: How to traverse through a JSON Object CodeUnit 06 NOV 2012

JSON has become just as big as XML in terms of being the format used to transfer data between AJAX driven web services, meaning that as a PHP developer you will no doubt be doing a lot of dealing with JSON objects.

The default way of grabbing JSON data returned by a web service is to call the built in json_decode function which generates what is known as a stdClass. These can be traversed much as you would a normal array using loops:

$jsondatastdclass = json_decode($jsoninput);
print_r($jsondataarray);

foreach ($jsondatastdclass as $object)
{
  foreach ($object as $property=>$value)
   {
     echo $property." has the value ". $value;
   } 
}

It’s not great, but it does work. However, later version of PHP do allow you to add a second parameter when calling the json_decode function, namely a boolean which then forces the function to return a normal associative array.

In practice:

$jsondataarray = json_decode($jsoninput, true);
print_r($jsondataarray);

echo $jsondataarray['data'][0];

And now you know.

JSONLint – A Good JSON Validator Software & Sites 05 MAR 2012

json-logoJSON, or JavaScript Object Notation, is a lightweight text-based open standard designed for human-readable data interchange. It is derived from the JavaScript scripting language for representing simple data structures and associative arrays, called objects. Despite its relationship to JavaScript, it is language-independent, with parsers available for many languages.

In other words, JSON is a good choice for data to be shuttled back and forth between web services via AJAX thanks to its clean and compact nature.

However, debugging a big chunk of JSON is not always the easiest task, particularly when it appears to be fault. Enter Chris Dary and his fantastic JSON validator and reformatter, JSONLint!

Simply copy or paste your JSON text into the big text box and hit the validate button, and JSONLint will make it look nice and spit out any validation errors it encounters while attempting to parse it. You can also feed it an URL, which it will then take and grab any JSON it detects from its source.

Additionally, if you are looking to squeeze your JSON to as small a form as possible, you can use JSONLint as a JSON compressor if you add ?reformat=compress to the URL.

Excellent free online tool, and well worth checking out if you do a lot of work with JSON.

Related Link: http://jsonlint.com/

PHP: How to Create a Simple JSON or XML Web Service CodeUnit 07 DEC 2011

Thanks to Twitter, the idea of accessible, useful, and more importantly, simple web services has really latched on in the world of web development. Bascially all a web service is, is a simple URL that when hit with or without specified parameters, returns some data in either JSON or XML (or quite frankly whatever you want it to return) format.

Here is a quick example to show you just how easy it is to develop a simple, basic web service of your own in PHP:

//database connection
$link = mysql_connect('localhost','username','password') or die('Cannot connect to the DB');
mysql_select_db('db_name',$link) or die('Cannot select the DB');

//format parameters. Note default of JSON for format parameter
$format = key_exists('format', $_POST) ? strtolower($_POST['format']) : 'json';
$format = in_array($format, array('json', 'xml')) ? $format : 'json';
$code = key_exists('code', $_POST) ? strtolower($_POST['code']) : 'survey';
$input = trim($code);

//output variables
$status = 0;
$name = '';
$message = '';

//check if we can find a record in the database
$campaignrs = mysql_query("SELECT `campaign-name` FROM `campaigns` WHERE `campaign-code` = '$input' LIMIT 1");
if (mysql_num_rows($campaignrs) > 0) {
        $campaign = mysql_fetch_assoc($campaignrs);
        $status = 1;
        $message = 'Valid Code';
        $name = $campaign['campaign-name'];
} else {
        $status = 0;
        $message = 'Invalid Code';
        $name = '';
}

//build output array
$output = array('status' => $status, 'message' => $message, 'name' => $name);

/* output in necessary format */
if ($format == 'json') {
    header('Content-type: application/json');
    echo json_encode($output);
} else {
    header('Content-type: text/xml');
    echo '';
    echo '' . $status . '';
    echo '' . $message . '';
    echo '' . $name . '';
    echo '';
}

 /* disconnect from the db */
mysql_close($link);

Simple. The web service provides an object with three keys, namely status, name, and message. You can control the output with the format switch, and the code parameter in this case is what we are using to initiate some sort of result or check.

That should be enough to get you up and running I reckon! :)

PHP: How to Implement jQuery Autocomplete using a JSON datasource CodeUnit 12 AUG 2011

The jQuery UI library is really useful in that it packages a number of jQuery-driven interactions, widgets, effects and utilities into a single package, ready for smooth integration and even easier deployment. One of the many available widgets in the jQuery UI library is Autocomplete, which makes adding autocomplete functionality to an ordinary text searchbox a doddle!

Let’s have a look how to implement this when using PHP to provide us with a separate JSON datasource then, shall we?

First, if your web page contains a normal textbox within a form that is used to conduct searches, you need to attach the jQuery UI autocomplete functionality with the following code snippet:

$('#datafilter-search-textbox').autocomplete({
            source: "ajax-search-autocomplete.php",
            minLength: 2});

Note the minLength setting of 2. It is often useful to set the number of characters needed to initiate the search so as to minimize the possible amount of search return values for efficiency’s sake.

As you can see, we have prompted the autocomplete widget to make use of a file called ajax-search-autocomplete.php as a datasource. This file should look something like this:

//… all your database setup stuff
$searchresults = array();
$searchterm = (key_exists('term', $_GET)) ? $_GET['term'] : '';

if (strlen($searchterm) > 0) {
    $results = mysql_query("SELECT `name`  FROM `myTable` WHERE `name` LIKE '%$searchterm%' ORDER BY `name` ASC");
    while ($result = mysql_fetch_assoc($results)) {
        $searchresults[] = $result['filter-name'];
    }
}
$searchresults = array_map("html_entity_decode_custom", $searchresults);
$searchresults = array_map("get_correct_utf8_mysql_string", $searchresults);
echo json_encode($searchresults);

And that is it. Load it up and try it out, and hey presto, you now have a nifty autocomplete that took you almost no time to implement! :)

Related Link: http://jqueryui.com/demos/autocomplete/

jQuery DataTables with Lots of Columns Crashes in IE CodeUnit 16 FEB 2011

If you are using the brilliant jQuery DataTables plugin to present your data in nifty dynamic tables, and are using it in a server-side loading context, you have no doubt encountered the issue when a table with a lot of columns (more than 20) fails to load (in other words stays in “processing” mode) when browsing using Internet Explorer (IE).

Mysteriously enough, it does however work in both Firefox and Chrome.

Although difficult to debug, the issue at hand is actually quite simple – essentially IE’s built-in GET size limit is kicking in at the most inopportune of times, meaning that incomplete JSON is heading back towards your page.

The simple solution is to force DataTables to use POST instead of GET for your server-side table, and to do this you need to add the following to your datatable definition:

$(document).ready(function() {
	$('#example').dataTable( {
		"bProcessing": true,
		"bServerSide": true,
		"sAjaxSource": "server_processing_post.php",
		"fnServerData": function ( sSource, aoData, fnCallback ) {
			$.ajax( {
				"dataType": 'json', 
				"type": "POST", 
				"url": sSource, 
				"data": aoData, 
				"success": fnCallback
			} );
		}
	} );
} );

As you can see from the above, the fnServerData variable allows you to specify the type of the ajax call being used, which means we can now force it to POST and thus eliminate our Internet Explorer large column table problem for good!

Nifty.

Related Link: http://datatables.net/

Accessing Values in Javascript JSON Objects with Keys containing Hyphens (Dashes) CodeUnit 12 AUG 2010

In Javascript, JSON objects (well, JS objects in general) have a great short hand little way of accessing values using the fullstop object notation.

In other words, using a JSON dataset looking like:

{“status”:”1″,”message-data”:”Success!”}

we could access the “status” value by simply entering:

alert(myobject.status);

However, if we tried the same thing with the “message-data” key, you will note that this will fall over syntactically straight away – all because of that silly hyphen (dash).

So the way around this?

Well you basically have to revert to the long notation format to get at the data associated with these keys, meaning that you would now need to do something like this:

alert(myobject[“message-data”]);

And now you know.

Nifty.

Magic Quotes and json_decode on Your Post Variables CodeUnit 15 APR 2010

Annoyingly, my PHP json_decode function was not working on my ajax pushed data, using the Javascript function json.stringify to post the data to the script in the first place.

However, even more annoying than this was that the code worked perfectly fine on the live server but not a damn did it want to run on my local machine!

So I scratched around using good old FireBug and after a little investigation and a whole lot of printing out of values, I noticed that the result of my stringified JSON data held in the POST variable was in fact looking different across the live and localhost server.

How so?

Well for a start there were delimited quotation marks appearing on the local machine instead of the plain old quotation marks showing up on the live server.

Now by delimited I mean the quotes were all being prefixed by slashes, meaning that a simple stripslashes on the JSON data would work perfectly well and solve my problem – but of course as we all can think for ourselves, that isn’t exactly the root of the problem now is it?

So what is adding in all these unwanted slashes then?

Well the answer of course is PHP’s magic_quotes_gpc ini setting. For those of you who don’t know, essentially this setting came in existence to help programmers who routinely forgot to delimit their strings when inputting them into databases, and also as a sort of automatic defense mechanism against simple SQL injection attacks. By turning magic quotes on, the server automatically delimits all incoming quotes held in the HTTP Request data (i.e. GET, POST, COOKIES) if they aren’t already delimited, meaning that in essence, it is possible for lazy programmers to get away with murder.

Of course, this has since been viewed as a bad idea and is deprecated from PHP 5.3.0.

Anyway, for some or other very strange reason, XAMPP has seen it fit to leave magic_quotes_gpc on in its default installation package and this was what was causing all the hassles on my local development environment.

Thankfully turning it off is as simple as walking to the php.ini file and changing the line magic_quotes_gpc = On to magic_quotes_gpc = Off.

However, if say the situation was reversed and the problem was sitting on a server whose ini file you can’t manipulate (and remember, magic quotes can’t be manipulated at runtime in the usual set ini fashion), here is a solution for you that actually works rather well:

function stripslashes_deep($value)
{
  $value = is_array($value) ? array_map("stripslashes_deep", $value) : stripslashes($value);
	return $value;
}

if (get_magic_quotes_gpc())
{
  $_POST = array_map("stripslashes_deep", $_POST);
  $_GET = array_map("stripslashes_deep", $_GET);
  $_COOKIE = array_map("stripslashes_deep", $_COOKIE);
  $_REQUEST = array_map("stripslashes_deep", $_REQUEST);
}

As you can see above, we first check to see if magic quotes are indeed turned on. If yes, run a recursive stripslashes function against each HTTP request data variable we can think of and presto, problem solved!

My PHP json_decode was now handling my javascript json.stringify JSON data perfectly! :)