Imagine having a deeply nested JS object like the example below that needs to be JSON-encoded:
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"}
]}
]
};
When using the native browser method JSON.stringify
, the expected JSON string is generated as shown in this 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"
}
]
}
]
}
However, things get complicated when attempting the same operation with a page that utilizes either PrototypeJS or json2.js.
In these cases, running JSON.stringify
on the same object yields a different JSON output as illustrated in this 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\"}]}]"
}
This discrepancy poses an issue because the resulting JSON cannot be decoded back into the original object provided to JSON.stringify
.
If anyone can shed light on why this difference occurs and what might be overlooked, your insights would be greatly appreciated.