Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

JSON Parse error: Unterminated string

I've met an usual problem when escaping a quote within the JSON parse function. If the escaped quote is present, in this case 'test"', it causes the following error 'SyntaxError: JSON Parse error: Unterminated string'.

var information = JSON.parse('[{"-1":"24","0":"","1":"","2":"","3":"0.0000","4":"","5":"0.00","6":"0.00","7":"1.00","8":"0","9":"false","10":"false","11":[""],"12":"","13":"","14":"test\""}]');

JSON Lint validates the JSON as valid.

like image 626
jdawg Avatar asked Dec 26 '14 11:12

jdawg


People also ask

What is unterminated string?

This JavaScript error unterminated string literal occurs if there is string which is not terminated properly. String literals must be enclosed by single (') or double (“) quotes.

What is a JSON parse error?

The "SyntaxError: JSON. parse: unexpected character" error occurs when passing a value that is not a valid JSON string to the JSON. parse method, e.g. a native JavaScript object. To solve the error, make sure to only pass valid JSON strings to the JSON.

How do I fix unexpected token in JSON error?

The "Unexpected token u in JSON at position 0" error occurs when we pass an undefined value to the JSON. parse or $. parseJSON methods. To solve the error, inspect the value you're trying to parse and make sure it's a valid JSON string before parsing it.


1 Answers

You'll have to double escape it, as in "test\\""

var information = JSON.parse('[{"-1":"24","0":"","1":"","2":"","3":"0.0000","4":"","5":"0.00","6":"0.00","7":"1.00","8":"0","9":"false","10":"false","11":[""],"12":"","13":"","14":"test\\""}]');

document.body.innerHTML = '<pre>' + JSON.stringify(information, null, 4) + '</pre>';

The first backslash escapes the second backslash in the javascript string literal. The second backslash escapes the quote in the JSON string literal.

So it's parsed twice, and needs escaping twice.

So even if it's valid JSON, you'll need one escape for javascript string literals that escapes the escape used in JSON.

like image 180
adeneo Avatar answered Sep 20 '22 12:09

adeneo