Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 660
j7nn7k Avatar asked Dec 02 '25 21:12

j7nn7k


2 Answers

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/

like image 194
Andy E Avatar answered Dec 04 '25 09:12

Andy E


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.

like image 23
darioo Avatar answered Dec 04 '25 09:12

darioo



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!