Skip to content Skip to sidebar Skip to footer

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. The structure of the JSON is out of my control, so I need t

Solution 1:

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

Solution 2:

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.

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

Post a Comment for "Missing Quotation Marks On Keys In Json"