Json parse() does not escape \" in javascript - javascript

I have java object which is converted as JSON string using
String paramMap = new ObjectMapper().writeValueAsString(custPolicy.getParamMap());
model.addAttribute("testTypeMap", paramMap );
In the .jsp page, on load I'm trying to parse the testTypeMap and get object back;
var paramMap = JSON.parse('${testTypeMap}');
showTestType('File content', 'LINUX', paramMap);
The object has double quotes (") in one of the fields, and it is escaped with backslash () when it is converted as JSON sting in java, that is why we see "\"" (from view source)
var paramMap = JSON.parse('{"Filepath":"/home/status.txt","Search expression":"\""}');
But the above line says, "Uncaught SyntaxError: Unexpected string".
I have seen few posts and they say it need two parses, one for javascript and one for JSON. I tried to replace \" with \\" ; but in javascript \" is always ", so I could not replace it;
Any pointer for what I miss here?

The problem is that you're not encoding the string in ${testTypeMap} as a JavaScript literal. I'm unsure how to do it specifically in your framework, but it's akin to HTML encoding a string, but for JavaScript instead.
However!
In your specific example you can avoid using JSON.parse because JSON is already in a format consumable by JavaScript.
var paramMap = ${testTypeMap};
showTestType('File content', 'LINUX', paramMap);
With the resulting source sent to browser looking like:
var paramMap = {"Filepath":"/home/status.txt","Search expression":"\""};

Actually I was not knowing how to replace \" with \\" in javascript, as \" is always represented as " (just one quote without backslash).
So I did this replace in server side after converting to a JSON string using Jackson's ObjectMapper as below:
String paramMap = new ObjectMapper().writeValueAsString(custPolicy.getParamMap());
// need to replace any \" with \\" in javascript side
paramMap = paramMap.replace("\\\"", "\\\\\"");
model.addAttribute("testTypeMap", paramMap );
Now in client-side it shows as below:
var paramMap = JSON.parse('{"Filepath":"/home/cavirin/status.txt","Search expression":"\\""}');
and this works fine as javascript parse is already taken care in server side.

Related

SyntaxError: Unexpected token \ in JSON at position

I'm trying to parse a String to JSON in NodeJS/Javascript, this is my string (which I cannot change, coming from an external database):
'{\\"value1\\":\\"XYZ\\",\\"value2\\":\\"ZYX\\"}'
I'm calling:
JSON.parse(row.raw_data)
But are getting:
SyntaxError: Unexpected token \ in JSON at position
I actually thought double escape was the correct way of escaping in string/JSON.
Your JSON is invalid. You've said you can't change it, which is unfortunate.
It looks like it's been double-stringified but then the outermost quotes have been left off. If so, you can fix it by adding " at each end and then double-parsing it, like this:
var str = '{\\"value1\\":\\"XYZ\\",\\"value2\\":\\"ZYX\\"}';
str = '"' + str + '"';
var obj = JSON.parse(JSON.parse(str));
console.log(obj);
Ideally, though, you'll want to go through the database and correct the invalid data.
I actually thought double escape was the correct way of escaping in string/JSON.
In JSON, strings are wrapped in double quotes ("), not double escapes. You only escape double quotes within strings (with a single \).
If you've been creating JSON strings manually (in code), don't. :-) Instead, create the structure you want to save, and then stringify it. Building JSON strings manually is error-prone, but a proper JSON stringifier will be reliable.

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.
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 are endline characters illegal in HTML string sent over ajax?

Within HTML, it is okay to have endline characters. But when I try to send HTML strings that have endline characters over AJAX to have them operated with JavaScript/jQuery, it returns an error that says that endline characters are illegal. For example, if I have a Ruby string:
"<div>Hello</div>"
and jsonify it with Ruby by to_json, and send it over ajax, parse it within JavaScript by JSON.parse, and insert that in jQuery like:
$('body').append('<div>Hello</div>');
then it does not return an error, but if I do a similar thing with a string like
"<div>Hello\n</div>"
it returns an error. Why are they legal in HTML and illegal in AJAX? Are there any other differences between a legal HTML string loaded as a page and legal HTML string sent over ajax?
string literals can contain line breaks, they just need to be escaped with a backslash like so:
var string = "hello\
world!";
However, this does not create a line break in the string, as it must be an explicit \n escape sequence. This would technically become helloworld. Doing
var string = "hello"
+ "world"
would be much cleaner
Specify the type of the ajax call as 'html'. Jquery will try to infer the type when parsing the response.
If the response is json, newlines should be escaped.
I'd recommend using a library to serialize json. You're unlikely to handle all the edge cases if you roll your own.
Strings in JavaScript MUST appear on a single line, with the exception of escaping that line:
var str = "abc \
def";
However note that the newline is escaped and will not appear in the string itself.
The best option is \n, but note that if it is already going through something that parses \n then you will need to double-escape it as \\n.
Seeing how you're already escaping the JSON properly by using to_json in Ruby, I do believe the bug is in jQuery; when there are newlines in the string it has trouble determining whether you meant to create a single element or a document fragment. This would work just fine:
var str = "<div>Hello\n</div>";
var wrapper = document.createElement('div');
wrapper.innerHTML = str;
$('body').append(wrapper);
Demo

Parse json string set by controller, in view

My MVC Controller contains a collection that I want to pass to the view, so I do:
// myCollection is a list of objects
var j = new JavaScriptSerializer();
ViewBag.Data = j.Serialize(myCollection);
And on the view inside JS
var data = $.parseJSON('#Html.Raw(ViewBag.Data)');
.. which expands to look something like:
var data = $.parseJSON('[{"Value":2,"Fullname":"Value"}]');
This works fine, but if my Json string contains a double quote it get's escaped with a backslash, and the parseJson fails, like this:
$.parseJSON('[{"Value":2,"Fullname":"Value \" with double quote"}]');
How do I fix that?
Whilst the following is valid JSON, it doesn't stay like that when the string is in JavaScript as it will unescape first:
'[{"Value":2,"Fullname":"Value \" with double quote"}]'
JavaScript will first unescape this to become:
'[{"Value":2,"Fullname":"Value " with double quote"}]'
When JSON comes along, it obviously sees an unexpected character since the quote is now looking to end the string. What you need to do is double-quote (\\" works) these somehow, whether you want to do it at the JS end or .NET end is probably entirely up to you.
However, there's really no need to parse this using JSON at all and you can just use it as an object literal like so:
var data = #Html.Raw(ViewBag.Data);
which will convert to:
var data = [{"Value":2,"Fullname":"Value \" with double quote"}];
.. which is perfectly valid.
why not just create custom function, and call parseJSON inside of it. but replace \" before that?
function parseJson(str){
var temp = str.replace('\"', '"');
return $.parseJSON(temp);
}

jQuery.parseJSON throws “Invalid JSON” error due to escaped single quote in JSON

I’m making requests to my server using jQuery.post() and my server is returning JSON objects (like { "var": "value", ... }). However, if any of the values contains a single quote (properly escaped like \'), jQuery fails to parse an otherwise valid JSON string. Here’s an example of what I mean (done in Chrome’s console):
data = "{ \"status\": \"success\", \"newHtml\": \"Hello \\\'x\" }";
eval("x = " + data); // { newHtml: "Hello 'x", status: "success" }
$.parseJSON(data); // Invalid JSON: { "status": "success", "newHtml": "Hello \'x" }
Is this normal? Is there no way to properly pass a single quote via JSON?
According to the state machine diagram on the JSON website, only escaped double-quote characters are allowed, not single-quotes. Single quote characters do not need to be escaped:
Update - More information for those that are interested:
Douglas Crockford does not specifically say why the JSON specification does not allow escaped single quotes within strings. However, during his discussion of JSON in Appendix E of JavaScript: The Good Parts, he writes:
JSON's design goals were to be minimal, portable, textual, and a subset of JavaScript. The less we need to agree on in order to interoperate, the more easily we can interoperate.
So perhaps he decided to only allow strings to be defined using double-quotes since this is one less rule that all JSON implementations must agree on. As a result, it is impossible for a single quote character within a string to accidentally terminate the string, because by definition a string can only be terminated by a double-quote character. Hence there is no need to allow escaping of a single quote character in the formal specification.
Digging a little bit deeper, Crockford's org.json implementation of JSON for Java is more permissible and does allow single quote characters:
The texts produced by the toString methods strictly conform to the JSON syntax rules. The constructors are more forgiving in the texts they will accept:
...
Strings may be quoted with ' (single quote).
This is confirmed by the JSONTokener source code. The nextString method accepts escaped single quote characters and treats them just like double-quote characters:
public String nextString(char quote) throws JSONException {
char c;
StringBuffer sb = new StringBuffer();
for (;;) {
c = next();
switch (c) {
...
case '\\':
c = this.next();
switch (c) {
...
case '"':
case '\'':
case '\\':
case '/':
sb.append(c);
break;
...
At the top of the method is an informative comment:
The formal JSON format does not allow strings in single quotes, but an implementation is allowed to accept them.
So some implementations will accept single quotes - but you should not rely on this. Many popular implementations are quite restrictive in this regard and will reject JSON that contains single quoted strings and/or escaped single quotes.
Finally to tie this back to the original question, jQuery.parseJSON first attempts to use the browser's native JSON parser or a loaded library such as json2.js where applicable (which on a side note is the library the jQuery logic is based on if JSON is not defined). Thus jQuery can only be as permissive as that underlying implementation:
parseJSON: function( data ) {
...
// Attempt to parse using the native JSON parser first
if ( window.JSON && window.JSON.parse ) {
return window.JSON.parse( data );
}
...
jQuery.error( "Invalid JSON: " + data );
},
As far as I know these implementations only adhere to the official JSON specification and do not accept single quotes, hence neither does jQuery.
If you need a single quote inside of a string, since \' is undefined by the spec, use \u0027 see http://www.utf8-chartable.de/ for all of them
edit: please excuse my misuse of the word backticks in the comments. I meant backslash. My point here is that in the event you have nested strings inside other strings, I think it can be more useful and readable to use unicode instead of lots of backslashes to escape a single quote. If you are not nested however it truly is easier to just put a plain old quote in there.
I understand where the problem lies and when I look at the specs its clear that unescaped single quotes should be parsed correctly.
I am using jquery`s jQuery.parseJSON function to parse the JSON string but still getting the parse error when there is a single quote in the data that is prepared with json_encode.
Could it be a mistake in my implementation that looks like this (PHP - server side):
$data = array();
$elem = array();
$elem['name'] = 'Erik';
$elem['position'] = 'PHP Programmer';
$data[] = json_encode($elem);
$elem = array();
$elem['name'] = 'Carl';
$elem['position'] = 'C Programmer';
$data[] = json_encode($elem);
$jsonString = "[" . implode(", ", $data) . "]";
The final step is that I store the JSON encoded string into an JS variable:
<script type="text/javascript">
employees = jQuery.parseJSON('<?=$marker; ?>');
</script>
If I use "" instead of '' it still throws an error.
SOLUTION:
The only thing that worked for me was to use bitmask JSON_HEX_APOS to convert the single quotes like this:
json_encode($tmp, JSON_HEX_APOS);
Is there another way of tackle this issue? Is my code wrong or poorly written?
Thanks
When You are sending a single quote in a query
empid = " T'via"
empid =escape(empid)
When You get the value including a single quote
var xxx = request.QueryString("empid")
xxx= unscape(xxx)
If you want to search/ insert the value which includes a single quote in a query
xxx=Replace(empid,"'","''")
Striking a similar issue using CakePHP to output a JavaScript script-block using PHP's native json_encode. $contractorCompanies contains values that have single quotation marks and as explained above and expected json_encode($contractorCompanies) doesn't escape them because its valid JSON.
<?php $this->Html->scriptBlock("var contractorCompanies = jQuery.parseJSON( '".(json_encode($contractorCompanies)."' );"); ?>
By adding addslashes() around the JSON encoded string you then escape the quotation marks allowing Cake / PHP to echo the correct javascript to the browser. JS errors disappear.
<?php $this->Html->scriptBlock("var contractorCompanies = jQuery.parseJSON( '".addslashes(json_encode($contractorCompanies))."' );"); ?>
I was trying to save a JSON object from a XHR request into a HTML5 data-* attribute. I tried many of above solutions with no success.
What I finally end up doing was replacing the single quote ' with it code ' using a regex after the stringify() method call the following way:
var productToString = JSON.stringify(productObject);
var quoteReplaced = productToString.replace(/'/g, "'");
var anchor = '<a data-product=\'' + quoteReplaced + '\' href=\'#\'>' + productObject.name + '</a>';
// Here you can use the "anchor" variable to update your DOM element.
Interesting. How are you generating your JSON on the server end? Are you using a library function (such as json_encode in PHP), or are you building the JSON string by hand?
The only thing that grabs my attention is the escape apostrophe (\'). Seeing as you're using double quotes, as you indeed should, there is no need to escape single quotes. I can't check if that is indeed the cause for your jQuery error, as I haven't updated to version 1.4.1 myself yet.

Categories

Resources