convert invalid JSON string to JSON

后端 未结 2 1115
旧巷少年郎
旧巷少年郎 2020-12-06 14:28

I have an invalid json string like following,

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

I tried to use JSON.parse to convert it to an object. howeve

相关标签:
2条回答
  • 2020-12-06 15:00

    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.

    0 讨论(0)
  • 2020-12-06 15:05

    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.

    0 讨论(0)
提交回复
热议问题