IE 8 new Feature for working with JSON
When I am lecturing "Microsoft Ajax" and I need to show some Ajax sample that uses JSON I explain to my students that they need to download some js files and place them in the web site in order for them to work with JSON in the client side.
When I am referring to working with JSON I usually mean 3 things:
1. Converting a string into a JSON object.
2. Converting an existing object into it's JSON string representation.
3. Converting an XML string into JSON object.
So for the first 2 I usually show the parse and stringify functions available in the free file to download from here: json2.js
At it turns out IE 8 has already a support for working with JSON. It contains a global object named "JSON" which has 2 methods. From msdn:
"An intrinsic object that provides methods to convert JScript values to and from the JavaScript Object Notation (JSON) format"
1. The JSON.stringify will convert an object (JavaScript object) into a JSON string:
var obj = new Object();
obj.x = 5;
obj.y = 6;
alert(JSON.stringify(obj));
will produce the string "{ 'x': 5, 'y': 6}"
2. The JSON.parse will convert a string into a JSON object.
var str = JSON.stringify(obj);
var obj2 = JSON.parse(str);
alert(obj2.x);
Some notes:
1. The JSON is available when the page is loaded (The engine is loaded).
2. You cannot create this JSON object using the new operator.