解析格式错误的json字符串,它周围没有双引号(Java Script)

时间:2013-11-19 23:35:54

标签: javascript json malformed

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

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

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

无论如何,我可能会从格式错误的JSON字符串中获得此结果吗?

2 个答案:

答案 0 :(得分:2)

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

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

答案 1 :(得分: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"
      }
   ]
}