0

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?

4

1 回答 1

1

使用JSON.parse的第二个参数来简单地在一个安全的 try 块中恢复你的代码:

JSON.parse( strOfJSON,  function(k,v){
  try{v=JSON.parse(v)}catch(y){}
 return v
});

OP测试代码的输出:

{
    "objects": [
        {
            "id": 1,
            "last-modified": 0,
            "created": 1,
            "name": "Test",
            "fields": {
                "k": "v",
                "k2": "v2",
                "k3": [
                    1,
                    2,
                    3
                ],
                "k4": {}
            }
        }
    ],
    "attribs": {}
}

您可以通过尝试将 json 标识为字符串来变得更花哨并跳过 try{},但是这个简单的天真代码可以工作,并展示了如何使用本机 JSON.parse() 函数来做您想做的事情。

于 2013-10-09T20:25:11.507 回答