convert invalid JSON string to JSON

馋奶兔 提交于 2019-11-26 21:54:12

问题


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?


回答1:


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.




回答2:


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.



来源:https://stackoverflow.com/questions/24462658/convert-invalid-json-string-to-json

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!