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

Parsing malformed json string which doesn't have double quotes around it (Java Script)

本文关键字:字符串 脚本 Java 错误 格式 json 周围没      更新时间:2023-09-26
{ ValidationError: { device_uuid: [ [Object] ] } }

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

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

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

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

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

我找到了非常酷的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"
      }
   ]
}