Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

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?

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

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
502 views
Welcome To Ask or Share your Answers For Others

1 Answer

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.

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...