简体   繁体   English

如何解析这种非标准的 JSON 格式?

[英]How do I parse this non-standard JSON format?

I want to know some process information ran on the VPS with PM2.我想知道用PM2在VPS上运行的一些进程信息。 But, with the JSON string return by PM2, we can't run JSON.parse() because the JSON is broken.但是,对于 PM2 返回的 JSON 字符串,我们无法运行JSON.parse() ,因为 JSON 已损坏。

An example of what PM2 returns: PM2 返回的示例:

'{data: 0, informations: "hello", name: "test"}'

But, if you know how the JSON.parse work, you know the problem.但是,如果您知道 JSON.parse 的工作原理,您就会知道问题所在。 We can't parse this string.我们无法解析这个字符串。

Do you have idea to resolve this problem with another function?你有想法用另一个功能解决这个问题吗?

Thanks in advance.提前致谢。

It seems like your string is encoded in regular JavaScript or JSON5.您的字符串似乎是用常规 JavaScript 或 JSON5 编码的。 JSON5 is a library which allows JSON to be defined in a similar way you would use it in regular JavaScript (without unnecessary " , etc.). Install the library and parse the string with JSON5.parse() . Reference: https://json5.org/ JSON5 是一个库,它允许以与在常规 JavaScript 中使用它的方式类似的方式定义 JSON(没有不必要的"等)。安装该库并使用JSON5.parse()解析字符串。参考: https:// json5.org/

Here is a solution for your specific non-json format.这是针对您的特定非 json 格式的解决方案。 The trick is to make sure to have double quotes around keys...诀窍是确保在键周围有双引号......

 function customParse(string){ return JSON.parse(string.replace(/\s|"/g, '') // Removes all spaces and double quotes.replace(/(\w+)/g, '"$1"') // Adds double quotes everywhere.replace(/"(\d+)"/g, '$1') // Removes double quotes around integers ) } // Testing the function let PM2_string = '{data: 0, informations: "hello", name: "test"}' let PM2_obj = customParse(PM2_string) // Result console.log(PM2_obj) console.log(PM2_obj.data) console.log(PM2_obj.informations) console.log(PM2_obj.name)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM