Search code examples
jqueryjsonparsingequalssign

"=" sign in JSON text causes parsing error


      "Cost to Implement \nRate 5 to 1\nHigh = 5\nLow = 1" 

as part of a JSON parses fine in jsonlint, but fails in Chrome with any of these approaches (each tried separately):

sections = $.parseJSON(myJSONstr);

sections = JSON.parse(myJSONstr);

sections = eval('(' + myJSONstr + ')');

When I remove the "=" signs from the string in the JSON, all is fine. My users will need the ability to enter the = sign in the text they enter. Is there a way around this?


Solution

  • It looks like you are entering the newline without escaping it. You need to escape the backslashes.

    The following fails because you're entering a raw newline into the JSON, they must be escaped

    var obj = JSON.parse('{"prop": "Cost to Implement \nRate 5 to 1\nHigh = 5\nLow = 1"}');
    

    Escape the backslashes

    // Works fine
    var obj = JSON.parse('{"prop": "Cost to Implement \\nRate 5 to 1\\nHigh = 5\\nLow = 1"}');
    

    Note that these new lines (and other characters that must escaped like tabs, backspaces...) will be automatically escaped if you correctly serialize your JSON objects. For example

    // Correctly parses the new line
    JSON.parse(JSON.stringify({prop: "Line1\nLine2\tAfterTab"}))