Skip to content Skip to sidebar Skip to footer

Parsing Complex JSON Javascript

I am able to parse JSON that returns simple data, with JSON.parse but I am having trouble with data that returns objects, dates, strings, etc.. var theData=JSON.parse(theData); So

Solution 1:

First and foremost, don't use synchronous XHR. Rewrite your JavaScript to be asynchronous.

function getDetail(cb) {
    var xhReq = new XMLHttpRequest();
    xhReq.open("POST", "ClientService.svc/REST/GetDetail", true);
    xhReq.onreadystatechange = function() {
        if (xhReq.readyState == 4) cb(xhReq.responseText);
    }
    xhReq.send(null);
}

// to call:

getDetail(function(data) {
    JSON.parse(data);
}

Second, your problem is not that JSON is being parsed incorrectly. It's your debugging call to alert. When you pass the serverResponse object, alert coerces the object into a string by calling the object's toString method, which simply returns '[object Object]'.

Try console.log. Objects can be inspected in the console.


Solution 2:

It actually sounds like this is working. If you call some thing like this:

alert(JSON.parse(serverResponse))

It will display [object Object] which is correct. If you call

alert(JSON.parse(serverResponse).appName)

You should see the appName. If you are not seeing "SyntaxError"s being thrown, JSON.parse() is working


Solution 3:

Your JSON format is wrong and the data needs to be a string.

So, this will work (I broke the lines to improve readability):

var data = "{" + 
    "    \"AppName\": \"TheName\", " + 
    "    \"AppUrl\": \"https:\/\/app\/icons\/unknown.png\", " + 
    "    \"aGUID\": \"45c055d2-2edc-d4444\", " + 
    "    \"DateCreated\": \"8\/23\/2012 11:04AM\", " +
    "    \"foo\": { " + 
    "        \"ID\": \"yser123\", " + 
    "        \"Name\":\"User\"" + 
    "    }" + 
    "}";
var obj = JSON.parse(data);
alert( obj.AppName );

Of course, if you use simple quotes as string delimiter, the code would be:

var data = '{' + 
    '    "AppName": "TheName", ' + 
    '    "AppUrl": "https:\/\/app\/icons\/unknown.png", ' + 
    '    "aGUID": "45c055d2-2edc-d4444", ' + 
    '    "DateCreated": "8\/23\/2012 11:04AM", ' +
    '    "foo": { ' + 
    '        "ID": "yser123", ' + 
    '        "Name":"User"' + 
    '    }' + 
    '}';

This not works:

var data = "{" + 
    "    'AppName': 'TheName', " + 
    "    'AppUrl': 'https:\/\/app\/icons\/unknown.png', " + 
    "    'aGUID': '45c055d2-2edc-d4444', " + 
    "    'DateCreated': '8\/23\/2012 11:04AM', " +
    "    'foo': { " + 
    "        'ID': 'yser123', " + 
    "        'Name': 'User'" + 
    "    }" + 
    "}";

jsFiddle: http://jsfiddle.net/9pmdm/1/


Post a Comment for "Parsing Complex JSON Javascript"