Deserializing a JSON into a JavaScript object

mj_ picture mj_ · Jun 27, 2011 · Viewed 340k times · Source

I have a string in a Java server application that is accessed using AJAX. It looks something like the following:

var json = [{
    "adjacencies": [
        {
          "nodeTo": "graphnode2",
          "nodeFrom": "graphnode1",
          "data": {
            "$color": "#557EAA"
          }
        }
    ],
    "data": {
      "$color": "#EBB056",
      "$type": "triangle",
      "$dim": 9
    },
    "id": "graphnode1",
    "name": "graphnode1"
},{
    "adjacencies": [],
    "data": {
      "$color": "#EBB056",
      "$type": "triangle",
      "$dim": 9
    },
    "id": "graphnode2",
    "name": "graphnode2"
}];

When the string gets pulled from the server, is there an easy way to turn this into a living JavaScript object (or array)? Or do I have to manually split the string and build my object manually?

Answer

user113716 picture user113716 · Jun 27, 2011

Modern browsers support JSON.parse().

var arr_from_json = JSON.parse( json_string );

In browsers that don't, you can include the json2 library.