I have a legacy API endpoint that, unfortunately, supports the output of flat JSON objects only. One of its outputs looks like this.
{
"objects": [
{
"id": "1",
"last-modified": "0",
"created": "1",
"name": "Test",
"fields": "{\"k\":\"v\",\"k2\":\"v2\",\"k3\":[1,2,3],\"k4\":{}}"
}
],
"attribs": {}
}
While this is valid JSON, any nested parts of the object will be stringified and returned as an overall object that is only one-key deep. When my JS retrieves this object, I attempt to deserialize all deserializable parts of the object, using a recursive function that I wrote.
var loads = function (obj) {
var i, buffer;
if (obj instanceof Array) {
buffer = [];
for (i = 0; i < obj.length; i++) {
buffer.push(loads(obj[i]));
}
return buffer;
} else if (obj instanceof Object) {
buffer = {};
for (i in obj) {
if (obj.hasOwnProperty(i)) {
buffer[i] = loads(obj[i]);
}
}
return buffer;
} else if (typeof obj === 'string') {
return JSON.parse(obj);
} else {
return JSON.parse(obj);
}
};
It is evident that the recursion is wrong, because many "unexpected token" and "unexpected identifier" errors are thrown by this function.
What mistake am I making in this function that prevents the full nested deserialization of stringified JSON values?