convert invalid JSON string to JSON

eded picture eded · Jun 28, 2014 · Viewed 7.7k times · Source

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?

Answer

Crow EH picture Crow EH · Jun 28, 2014

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.