简体   繁体   English

在JSON中的键上缺少引号

[英]missing quotation marks on keys in JSON

I have a string containing malformed JSON which is being provided to me where the keys are missing the quotation marks. 我有一个包含格式错误的JSON的字符串,它提供给我,其中键缺少引号。 The structure of the JSON is out of my control, so I need to work with what I have. JSON的结构不受我的控制,所以我需要使用我拥有的东西。 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. 我已经找到了解析PL中使用JavaScript中的格式错误的JSON工作的解决方案,但是其中一个值包含RegEx匹配的URL并将其转换为另一个键,如值,从而导致真正损坏的JSON。 Any ideas? 有任何想法吗?

I have also looked at jsonrepair , but not having much success there. 我也看过jsonrepair ,但在那里没有取得多大成功。

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

.replace(/(['"])?([a-zA-Z0-9_]+)(['"])?:([^\/])/g, '"$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. 因此, 如果您信任源 ,则可以将文本括在括号中并对其进行eval

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

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

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