convert invalid JSON string to JSON

I have an invalid json string like following,

"{one: 'one', two: 'two'}"

I tried to use JSON.parse to convert it to an object. however, this is not valid json string. Is there any functions can convert this invalid format into a valid json string or directly convert into an object?

Answers:

Answer

IF your example syntax is the same as your real JSON, JSONLint says you need double quote for the name AND the value.

In this case only, use these replace calls:

var jsontemp = yourjson.replace((/([\w]+)(:)/g), "\"$1\"$2");
var correctjson = jsontemp.replace((/'/g), "\"");
//yourjson = "{one: 'one', two: 'two'}"
//jsontemp = "{"one": 'one', "two": 'two'}"
//correctjson = "{"one": "one", "two": "two"}"

However you should try to work with a valid Json in the first place.

Answer

If the question is "can I convert invalid JSON into valid JSON", in the general case the answer is obviously "no"; where would you even start with a string like "[email protected]!~~"?

In this particular case, the JSON is only invalid because the property names are not quoted; as JavaScript, the string is valid and could be parsed using, for example,

var myObj = eval( "x=" + myString );

or better

var myObj = (new Function("return " + myString))();

However, this is potentially very unsafe and you should not do it unless you are positive the string cannot cause harm (which seems unlikely if you aren't in a position to generate valid JSON in the first place). It also won't help you if the JSON code is invalid in other ways, and it will fail if the property names are not valid JS identifiers.

For a proper answer it would be useful to know more about the context of this question.

Tags

Recent Questions

Top Questions

Home Tags Terms of Service Privacy Policy DMCA Contact Us

©2020 All rights reserved.