Why is it that
//Code
JSON.parse("{'name':'Khushal Khan'}");
results in this error
//Resposnse
SyntaxError: Unexpected token '
while this works perfectly
//Code
JSON.parse('{"name":"Khushal Khan"}');
Output:
//Response
Object {name: "Khushal Khan"}
The problem is the type of quote used in your JSON string, not the outer quotes. The JSON specification only allows for double quoted strings. You could use either type of quote to actually pass your JSON string to the parse() function, though.
From the JSON spec:
The problem is not that your JavaScript string uses " characters but that your JSON strings do not.
JSON is not JavaScript. JSON strings must be delimited by " characters.
From the specification:
string = quotation-mark *char quotation-mark
and
quotation-mark = %x22 ; "
Problem is not with double quoted string, but the json should have no single quotes as delimiters.
Related
I am trying to learn more about the core functionality of the JSON.parse() method, but I cannot understand why this string returns an error:
JSON.parse('["foo\\"]'); // > "Unexpected end of input"
Why does this not return ["foo\"]?
Because the string isn't terminated, because the second " is escaped by \, because the data you're parsing is:
["foo\"]
You can confirm this yourself with
var s = '["foo\\"]';
alert(s); // or
console.log(s);
This is because of the cumulative escape action of \ in JS and JSON level in your expression.
Your string ["foo\\"]
Escaped by JS to be ["foo\"] first because its double \\
Now it is sent to JSON.parse like ["foo\"] which escapes the "
So, it is an un-terminated string for JSON parser.
If you need to parse ["foo\\"] in json level, assemble the js string to be escaped to this. Which is ["foo\\\\\"].
TEST.
s = '["foo\\\\\"]';
console.log(s); //'["foo\\"]'
console.log(JSON.parse(s);) // ["foo\"]
Can someone explain why when I try to use JSON.parse() on the operators "+", "-", "*", "/" it returns:
SyntaxError: Unexpected token +
SyntaxError: Unexpected token -
SyntaxError: Unexpected token *
SyntaxError: Unexpected token /
I am passing a string which is valid but it will not return the operator as itself. There is nothing in the documentation that would explain why this is invalid: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/JSON/parse
Any help is appreciated. Thank you.
Edit for clarity*
In the documentation, the cases below are all valid. They are arbitrary strings being passed to JSON.parse(). You can verify these examples in your console. My question is why passing an operator as a string will not return the operator.
JSON.parse('{}'); // {}
JSON.parse('true'); // true
JSON.parse('"foo"'); // "foo"
JSON.parse('[1, 5, "false"]'); // [1, 5, "false"]
JSON.parse('null'); // null
In JSON, strings need to be in double quotes. So if you want a JSON string that contains an operator, it needs to be quoted.
var json = '"+"';
var result = JSON.parse(json);
alert(result);
This will alert +.
The single quotes are for the Javascript literal, the double quotes are part of the JSON syntax.
JSON it's a string that contains key value pairs. JSON.parse() it's a function that will return object with properties named with key, and it mean that you can't use +, -, /, * as name for object property. That's why you receive this error.
Operators are not valid json. JSON.parse is for converting a json formatted string into corressponding javascript types and objects. You are looking for eval. eval executes a string as if it were javascript code.
Information on eval
Information on valid json
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.
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.
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\\""}]');
Putting doubleslash worked for me...at least in console..give it a try..
I fixed this problem in my spring boot app with #RestController by Using #IgnoreJson
--------- class book ---------------
#OneToMany(mappedBy = "book")
private Set<Chapitre> chapitres = new TreeSet<>();
--------- class chapitre -----------
#ManyToOne(cascade = CascadeType.MERGE)
#JsonIgnore
private Book book;
Here is the issue : use \' instead of \" at last array of object
\"
\'
Why is it that
//Code
JSON.parse("{'name':'Khushal Khan'}");
results in this error
//Resposnse
SyntaxError: Unexpected token '
while this works perfectly
//Code
JSON.parse('{"name":"Khushal Khan"}');
Output:
//Response
Object {name: "Khushal Khan"}
The problem is the type of quote used in your JSON string, not the outer quotes. The JSON specification only allows for double quoted strings. You could use either type of quote to actually pass your JSON string to the parse() function, though.
From the JSON spec:
The problem is not that your JavaScript string uses " characters but that your JSON strings do not.
JSON is not JavaScript. JSON strings must be delimited by " characters.
From the specification:
string = quotation-mark *char quotation-mark
and
quotation-mark = %x22 ; "
Problem is not with double quoted string, but the json should have no single quotes as delimiters.
Can someone pleas explain to me why json which contains a string with double quotes will break $.parseJSON?
This works:
[{"type":"message","content":{"user":"tomasa", "time":"1321722536", "text":"asdasdasd"}}]
This also works:
[{"type":"message","content":{"user":"tomasa", "time":"1321723267", "text":"""}}]
However this will cause $.jsonParse to not return anything (I am assuming becuase it is a malformed json string:
[{"user":"tomasa", "time":"1321723278", "text":""""}}]
You have an extra } at the end.
}}]
You should run troublesome JSON markup through http://jsonlint.com/
Parse error on line 6:
...""" }}]
---------------------^
Expecting ',', ']'
It's not the " or " but the extraenous } you have:
[{"user":"tomasa", "time":"1321723278", "text":""""}}]
^
It crashes because of the double }.
>>> $.parseJSON('[{"user":"tomasa", "time":"1321723278", "text":""""}}]')
SyntaxError: JSON.parse: expected ',' or ']' after array element
(function(a,b){function cy(a){return f...h]&&f.event.trigger(c,d,b.handle.elem
But this works:
>>> $.parseJSON('[{"user":"tomasa", "time":"1321723278", "text":""""}]')
[Object { user="tomasa", time="1321723278", text=""""}]
$.parseJSON is looking for the name of the object in double quotes and the value of that object in single quotes. Is this what you are asking?
Because the JSON specification specifically states that string elements are defined as:
string
""
" chars "
In other words, string values must be surrounded by double quotes in order to be valid JSON.
Edited to add:
My answer above is correct for the original question as it was posted a few seconds ago, which was basically "why does jQuery.parseJSON fail when double quotes aren't used", but then the OP modified the question to include an example that demonstrates his/her actually problem, which has nothing to do with the quotes at all.