1
{ ValidationError: { device_uuid: [ [Object] ] } }

我喜欢将此字符串转换为 JSON 格式,就像

{ "ValidationError": { "device_uuid": [ [Object] ] } }

无论如何,我可以从格式错误的 JSON 字符串中得到这个结果吗?

4

2 回答 2

2

假设您确定格式不正确的字符串是安全的并且只是格式错误的 JSON(即不会执行任何其他 javascript),您可以先 eval 然后 JSON.stringify 它。

JSON.stringify(eval('(' + myString + ')'));

于 2013-11-19T23:40:10.177 回答
1

我发现了非常酷的 javascript 库。 https://github.com/freethenation/durable-json-lint

它帮助我格式错误的 json 字符串转换为格式正确的 json 字符串!

durableJsonLint = require('durable-json-lint');
console.log(durableJsonLint('{name:"value", \'array\':[call(), 0x11]}'))
// The above code would print the following to the console
{
   "json":'{"name":"value", "array":[null, 17]}',
   "errors":[{
         "column":1,
         "description":"Keys must be double quoted in Json. Did you mean \"name\"?",
         "lineNumber":1,
         "status":"correctable"
      },{
         "column":15,
         "description":"Json strings must use double quotes",
         "lineNumber":1,
         "status":"correctable"
      },{
         "column":24,
         "description":"You can not make function calls in Json. Do you think I am a fool?",
         "lineNumber":1,
         "status":"fail"
      },{
         "column":32,
         "description":"Invalid Json number",
         "lineNumber":1,
         "status":"correctable"
      }
   ]
}
于 2013-11-19T23:58:14.627 回答