Noticing the weird difference between the various JSON.stringify implementations

Let's say I have a fairly nested JS object like this, and I need to JSON code it:

var foo = { "totA": -1, "totB": -1, "totC": "13,052.00", "totHours": 154, "groups": [ {"id": 1, "name": "Name A", "billingCodes": [ {"bc": "25", "type": "hours", "hours": "5", "amount": "$25.00"} ]} ] }; 

If I JSON-encode it using my own JSON.stringify browser (tested in Chrome, Firefox, IE9 / 10), I return a JSON string that looks like this (which I expect):

Native JSON.stringify JSFiddle example

 { "totA": -1, "totB": -1, "totC": "13,052.00", "totHours": 154, "groups": [ { "id": 1, "name": "Name A", "billingCodes": [ { "bc": "25", "type": "hours", "hours": "5", "amount": "$25.00" } ] } ] } 

Strange things happen if I try to do the same on a page that uses PrototypeJS or json2.js .

In this case, JSON.stringify on the same object returns the following JSON to me:

ProtypeJS JSON.stringify JSFiddle Example

 { "totA": -1, "totB": -1, "totC": "13,052.00", "totHours": 154, "groups": "[{\"id\": 1, \"name\": \"Name A\", \"billingCodes\": [{\"bc\": \"25\", \"type\": \"hours\", \"hours\": \"5\", \"amount\": \"$25.00\"}]}]" } 

Obviously, this is a problem because it does not JSON decode the same object that was originally passed to JSON.stringify .

Can someone clarify what is happening and why does this difference exist?

What am I missing?

+7
json javascript
source share
1 answer

This is because native JSON.stringify refers to toJSON methods, and Prototype adds them everywhere. Unfortunately, native and Prototype seem to understand toJSON differently: while native expects it to return a string that is used as a literal value, Prototype toJSON returns pieces of already formatted JSON that are intended to be used as is, Hence the discrepancy.

This works great:

 delete Array.prototype.toJSON; document.getElementById('out').innerHTML += JSON.stringify(foo); 

http://jsfiddle.net/Ky3tv/2/

Additionally, this seems to be fixed in Prototype 1.7. I assume that now they check their own JSON before adding their toJSON methods.

+7
source share

All Articles