Friday, March 9, 2018

JSON in Javascript

JSON (in Javascript) is a string!
People ofetn assume all Javascript objects is JSON and JSON is a Javascript object. This is incorrect.
In Javascript var x = {x:y} is not JSON, this is a Javascript object. The two are not the same thing. The JSON equivalent (represented in the Javascript language) would be var x = '{"x":"y"}'x is an object of type string not an object in it's own right. To turn this into a fully fledged Javascript object you must first parse it, var x = JSON.parse('{"x":"y"}');x is now an object but this is not JSON anymore.

When working with JSON and JavaScript, you may be tempted to use the eval function to evaluate the result returned in the callback, but this is not suggested since there are two characters (U+2028 & U+2029) valid in JSON but not in JavaScript.
Hence, one must always try to use Crockford's script that checks for a valid JSON before evaluating it.
Below is an example on how to use the JSON Parser (with the json from the above code snippet):
//The callback function that will be executed once data is received from the server
var callback = function (result) {
var johnny = JSON.parse(result);
//Now, the variable 'johnny' is an object that contains all of the properties
//from the above code snippet (the json example)
alert(johnny.firstName + ' ' + johnny.lastName); //Will alert 'John Smith'
};
The JSON Parser also offers another very useful method, stringify. This method accepts a JavaScript object as a parameter, and outputs back a string with JSON format. This would be useful when you want to send data back to the server:
var anObject = {name: "Andreas", surname : "Grech", age : 20};
var jsonFormat = JSON.stringify(anObject);
//The above method will output this: {"name":"Andreas","surname":"Grech","age":20}
The above two methods (parse and stringify) also take a second parameter, which is a function that will be called for every key and value at every level of the final result, and each value will be replaced by result of your inputted function.
Check this to format and validate JSON: JSON formatter online tool.

No comments:

Post a Comment