Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 947
eded Avatar asked Jun 28 '14 01:06

eded


2 Answers

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.

like image 102
Crow EH Avatar answered Sep 21 '22 15:09

Crow EH


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 "$@!~~"?

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.

like image 39
bobtato Avatar answered Sep 20 '22 15:09

bobtato