j7nn7k
j7nn7k

Reputation: 18612

Problem parsing JSON

I encounter problems tring to consume a third party web servive in JSON format. The JSON response from the server kinda looks like this:

{
    "ID":10079,
    "DateTime":new Date(1288384200000),
    "TimeZoneID":"W. Europe Standard Time",
    "groupID":284,
    "groupOrderID":10
}

I use JavaScript with no additional libs to parse the JSON.

//Parse JSON string to JS Object            
var messageAsJSObj = JSON.parse(fullResultJSON);

The parsing fails. A JSON validatior tells me, "new Date(1288384200000)" is not valid.

Is there a library which could help me parse the JSON string?

Upvotes: 3

Views: 2835

Answers (4)

Andy E
Andy E

Reputation: 344783

Like others have pointed out, it's invalid JSON. One solution is to use eval() instead of JSON.parse() but that leaves you with a potential security issue instead.

A better approach might be to search for and replace these offending issues, turning the data into valid JSON:

fullResultJSON = fullResultJSON.replace(/new Date\((\d+)\)/g, '$1');

You can even go one step further and "revive" these fields into JavaScript Date objects using the second argument for JSON.parse():

var messageAsJSObj = JSON.parse(fullResultJSON, function (key, value) {
    if (key == "DateTime")
        return new Date(value);

    return value;
}); 

Here's an example: http://jsfiddle.net/AndyE/vcXnE/

Upvotes: 5

darioo
darioo

Reputation: 47213

Your example is not valid JSON, since JSON is a data exchange technology. You can turn your example into a Javascript object using eval:

var almostJSON = "{
    "ID":10079,
    "DateTime":new Date(1288384200000),
    "TimeZoneID":"W. Europe Standard Time",
    "groupID":284,
    "groupOrderID":10,
}";

and then evaling it:

var myObject = eval('(' + almostJSON + ')');

Then, myObject should hold what you're looking for.

Note that functions are not allowed in JSON because that could compromise security.

Upvotes: 3

fcalderan
fcalderan

Reputation:

Parsing fails because all you can parse in a json object are null, strings, numbers, objects, arrays and boolean values so new Date(1288384200000), cannot be parsed

You have also another problem, last property shouldn't have the trailing comma.

Upvotes: 0

rbhro
rbhro

Reputation: 208

try var obj = eval('(' + fullResultJSON + ')'); and you'll have the object like Pekka said. Don't forget to use the extra '()' though. And indeed json should have both property and value enclosed in quotes.

Upvotes: 0

Related Questions