JSON中的键上缺少引号

时间:2021-09-19 06:19:22

I have a string containing malformed JSON which is being provided to me where the keys are missing the quotation marks. The structure of the JSON is out of my control, so I need to work with what I have. I have found the solution that the OP posts in Parsing malformed JSON in JavaScript works, however one of the values contains a URL that the RegEx matches and transforms it into another key like value, resulting in really broken JSON. Any ideas?

我有一个包含格式错误的JSON的字符串,它提供给我,其中键缺少引号。 JSON的结构超出了我的控制范围,所以我需要使用我拥有的东西。我已经找到了PL在Parsing格式错误的JSON中发布的解决方案,但其中一个值包含一个RegEx匹配的URL,并将其转换为另一个键,如值,导致真正损坏的JSON。有任何想法吗?

I have also looked at jsonrepair, but not having much success there.

我也看过jsonrepair,但在那里没有取得多大成功。

2 个解决方案

#1


5  

This should do it. All you needed to do was identify when a colon was followed by a forward-slash (like in http://) instead of in isolation. Note that this will fail in the event that one of your JSON values has a colon in it, so it may need more improvement for your use case.

这应该做到这一点。你需要做的就是确定冒号后面跟着一个正斜杠(比如http://)而不是孤立的。请注意,如果您的某个JSON值中包含冒号,则会失败,因此可能需要对您的用例进行更多改进。

.replace(/(['"])?([a-zA-Z0-9_]+)(['"])?:([^\/])/g, '"$2":$4');

#2


4  

If the only thing wrong with the JSON is property names without quotes, then it is still a valid JavaScript object literal even though it isn't valid JSON.

如果JSON唯一错误的是没有引号的属性名称,那么它仍然是一个有效的JavaScript对象文字,即使它不是有效的JSON。

So, if you trust the source, you can wrap the text in parentheses and eval it.

因此,如果您信任源,则可以将文本括在括号中并对其进行评估。

This will be simpler and more reliable than any regular expression.

这比任何正则表达式更简单,更可靠。

Example:

var badJSON = '{ a: "b" }';
var obj = eval( '(' + badJSON + ')' );
console.log( obj );    // Logs: Object {a: "b"}
console.log( obj.a );  // Logs: b

#1


5  

This should do it. All you needed to do was identify when a colon was followed by a forward-slash (like in http://) instead of in isolation. Note that this will fail in the event that one of your JSON values has a colon in it, so it may need more improvement for your use case.

这应该做到这一点。你需要做的就是确定冒号后面跟着一个正斜杠(比如http://)而不是孤立的。请注意,如果您的某个JSON值中包含冒号,则会失败,因此可能需要对您的用例进行更多改进。

.replace(/(['"])?([a-zA-Z0-9_]+)(['"])?:([^\/])/g, '"$2":$4');

#2


4  

If the only thing wrong with the JSON is property names without quotes, then it is still a valid JavaScript object literal even though it isn't valid JSON.

如果JSON唯一错误的是没有引号的属性名称,那么它仍然是一个有效的JavaScript对象文字,即使它不是有效的JSON。

So, if you trust the source, you can wrap the text in parentheses and eval it.

因此,如果您信任源,则可以将文本括在括号中并对其进行评估。

This will be simpler and more reliable than any regular expression.

这比任何正则表达式更简单,更可靠。

Example:

var badJSON = '{ a: "b" }';
var obj = eval( '(' + badJSON + ')' );
console.log( obj );    // Logs: Object {a: "b"}
console.log( obj.a );  // Logs: b