JSON.stringify doesn't escape? - javascript

I'm using `JSON.stringify? to stringify an object, but the quotes are not escaped? Am I misunderstanding that it's suppose to escape the quotes?
This is outputted into the template without any of the quotes being escaped:
{"console":{"free":false}}

stringify the object twice does the trick
console.log(JSON.stringify(JSON.stringify({"console":{"free":false}})));
// "{\"console\":{\"free\":false}}"

It doesn't escape characters, no, there's encodeURIComponent for that, and you can use them together, as in encodeURIComponent(JSON.stringify(obj))

The quotes around property names are not supposed to be escaped, only quotes inside strings. Your JSON is fine :)

Without the offending code to inspect, I'm wondering if something else is happening. As a test...
<div id="test"/>
var ex = {'test':'This is "text".'};
$('#test').text(JSON.stringify(ex));
Outputs: {"test":"This is \"text\"."} (< Note the escaped double quotes)
http://jsfiddle.net/userdude/YVGbH/

Related

JSON.parse failing on valid Json. Have escaped control characters.If

I've escaped control characters and am feeding my validated JSON into JSON.parse and jQuery.parseJSON. Both are giving the same result.
Getting error message "Unexpected token $":
$(function(){
try{
$.parseJSON('"\\\\\"$\\\\\"#,##0"');
} catch (exception) {
alert(exception.message);
}
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js"></script>
Thanks for checking out this issue.
What's happening here is that there are two levels of backslash removal being applied to the string. The first is done by the browser's JavaScript engine when it parses the single-quoted string. In JavaScript, single-quoted strings and double-quoted strings are exactly equivalent (other than the fact that single-quotes must be backslash-escaped in single-quoted strings and double-quotes must be backslash-escaped in double-quoted strings); both types of strings take backslash escape codes such as \\ for backslash, \' for single-quote (redundant but accepted in double-quoted strings), and \" for double-quote (redundant but accepted in single-quoted strings).
In your JavaScript single-quoted string literal you have several instances of this kind of thing, which are meant to be valid JSON double-quoted strings:
"\\\\\"$\\\\\"#,##0"
After the browser has parsed it, the string contains exactly the following characters (including the outer double-quotes, which are unremoved because they are contained in a single-quoted string):
"\\"$\\"#,##0"
You can see that each consecutive pair of backslashes became a single literal backslash, and the two cases of an odd backslash followed by a double-quote each became a literal double-quote.
That is the text that is being passed as an argument to $.parseJSON, which is when the second level of backslash removal occurs. During JSON parsing of the above text, the leading double-quote signifies the start of a JSON string literal, then the pair of backslashes is interpreted as a single literal backslash, and then the immediately following double-quote terminates the JSON string literal. The stuff that follows (dollar, backslash, backslash, etc.) is invalid JSON syntax.
The problem is that you've embedded valid JSON in a JavaScript single-quoted string literal, which, although it happens to be valid JavaScript syntax by fluke (it wouldn't have been if the JSON contained single-quotes, or if you'd tried using double-quotes to delimit the JavaScript string literal), no longer contains valid JSON after being parsed by the browser's JavaScript engine.
To solve the problem, you have to either manually escape the JSON content to be properly embedded in a JavaScript string literal, or load it independently of the JavaScript source, e.g. from a flat file.
Here's a demonstration of how to solve the problem using your latest example code:
$(function() {
try {
alert($.parseJSON('{"key":"\\\\\\\\\\"$\\\\\\\\\\"#,##0"}').key); // works
alert($.parseJSON('{"key":"\\\\\"$\\\\\"#,##0"}').key); // doesn't work
} catch (exception) {
alert(exception.message);
}
});
http://jsfiddle.net/814uw638/2/
Since JavaScript has a simple escaping scheme (e.g. see http://blogs.learnnowonline.com/2012/07/19/escape-sequences-in-string-literals-using-javascript/), it's actually pretty easy to solve this problem in the general case. You just have to decide in advance how you're going to quote the string in JavaScript (single-quotes are a good idea, because strings in JSON are always double-quoted), and then when you prepare the JavaScript source, just add a backslash before every single-quote and every backslash in the embedded JSON. That should guarantee it will be perfectly valid, regardless of the exact JSON content (provided, of course, that it is valid JSON to begin with).
In your original problem, why do you need to do JSONparse in the first place? You could have easily gotten the object you wanted by just doing
var o = { blah }
by manually removing the single quotes you have around the curly braces rather than doing
$.JSONparse('{blah}')
Is there any reason for evaluating the string first (ie var s = '{blah}' and then doing $.JSONparse(s)) which is what your original code was doing? There shouldn't be a case where this is necessary. Since you mentioned somewhere that the string was produced by JSON.stringify, there shouldn't be a scenario where you need to explicitly store it into a variable (ie copy and paste it and put quotes around it).
The main problem here is the string produced by JSON.stringify, which is properly escaped, has been 'evaluated' once when you manually put braces around it. So the key is to make sure the string doesn't get 'evaluated'
Even if you wanted to pass the stringified variable to database or anything, there is no need to explicitly use quotes. One could do
var s = JSON.stringify(obj);
db.save("myobj",s)
var newObj = JSON.parse(db.load("myobj"))
The string is stored verbatim without getting evaluated, so that when you retrieve it, you would have the exact same string.

jquery escaping quotes not quite right

I have attempted escaping quotes out from this jquery bit of code and I'm not quite getting it. As well as the correct answer could I get the format for escaping quotes in jquery? Specifically I'm only trying to put the rdata.result[i].name variable into a string to pass it over. Thanks!
filling += "<a onclick=\"inserttictac("+rdata.result[i].uid+","+rdata.script[0]+",\'"+rdata.result[i].name+"\',"+rdata.result[i].front+","+rdata.result[i].back+","+rdata.result[i].side+")\'>Select</a>";
You don't need to escape the single quotes, only the double quotes.
You are using double quotes for string definition, so only escape those.
filling += "<a onclick=\"inserttictac("+rdata.result[i].uid+","+rdata.script[0]+",'"+rdata.result[i].name+"',"+rdata.result[i].front+","+rdata.result[i].back+","+rdata.result[i].side+")\">Select</a>";

Escaping javascript variable double quotes

I'm using Ajax calls to get some variables data from the DB.
some of my data stored on the database contains double quotes (").
when I'm trying to display the variable :
value="'+ucontent+'"
the string gets cut in the middle (of course)
I have tried using escape() but im getting a non readable result - something with %4%2 etc...
how can i escape the double quotes in the variable and still keep a readable string...
BTW - I'm using UTF8 characters.
decodeURIComponent()
might be helpful
what escape actually does is replace some characters with a hexadecimal escape sequence.
That is the reason why you are getting unreadable string like %4%2.
Depends on what language in server side you are using.
If it is php, then use json_encode to encode the response string.
If it is ruby(rails), then use escape_javascript to escape the response string.
You can just use \" if you don't use an encoder. See this.

escape special characters in javascript (jquery) function

I have this line that appending this in jquery:
$('#league2').append("<input type=\"button\" id=\"2btn\" value=\"1.2\" class=\"butta\" onmousedown=\"active('exam\'ple','awayteam')");
Notice the "exam\'ple"... i escaped the ' with \'
so when clicking the button, the function active should work.
this is the function active:
function active(hometeam,awayteam){
alert("if this is alerted, it works!");
}
when i click the button it should alert "if this is alerted, it works!", but it's not alerting it. and it think because when i use the function, this is the outpot:
function active(exam\'ple,awayteam){
when i appending the same thing with a word that does not contain " ' ", it is working.
You need to escape the backslash in your parameters for the active function, instead of the apostrophe.
$('#league2').append("<input type=\"button\" id=\"2btn\" value=\"1.2\" class=\"butta\" onmousedown=\"active('exam\\'ple','awayteam')");
To escape a string to append it to that code with php, you can use regular expressions. The following will work in your case.
// Replaces a backslash with four backslashes: The 'append' function will interpret it as two backslashes; the 'active' function, as only one.
$str = preg_replace("/\\\\/", "\\\\\\\\\\\\\\\\", $str);
// Replaces an apostrophe with two backslashes and an apostrophe, then javascript will append only one backslash and an apostrophe, escaping that way an apostrophe.
$str = preg_replace("/'/", "\\\\\\\\'", $str);
// Replaces quotations with a backslash and quotations: the quotations will be escaped inside the append function, so one quotations will be printed out on your HTML
$str = preg_replace("/\"/", "\\\\\"", $str);
If you don't know what a regular expression (regex) is, I suggest you researching a bit about how to use them. They will help you a lot.
EDIT: By some reason, the last program needed double of backslashes to work. Updated.
You don't need to escape single quotes when the string is double-quoted. It's best practice to wrap the whole string in single quotes, allowing you to use double quotes without the need to escape. (or single quotes with it all wrapped up in doubles).
For example:
$("#thing").append('<div id="foo" class="bar" style="color:black;" onclick="foobar()"></div>');
Your code's a little more complicated, because there's multiple levels (have you considered jQuery's click?):
$('#league2').append('<input type="button" id="2btn" value="1.2" class="butta" onmousedown="active('exam\'ple','awayteam')');

Whats wrong with this JSON syntax?

Am trying this on my chrome debugger console, and am getting a SyntaxError;
JSON.parse("[{"name":"gath","age":10}]");
>SyntaxError
What is the correct way of parsing the JSON string?
Please note this question is a follow up to my earlier one, which am yet to get an answer!
You need to escape your double-quotes.
JSON.parse("[{\"name\":\"gath\",\"age\":10}]");
or, for better readabilty, define the string with single quotes:
JSON.parse('[{"name":"gath","age":10}]');
JSON.parse("[{\"name\":\"gath\",\"age\":10}]");
You cant have double quotes inside double quotes
You need to escape the "
or do JSON.parse('[{"name":"gath","age":10}]');
Enclose it in single quotes and it will parse correctly.
JSON.parse('[{"name":"gath","age":10}]');
Object
age: 10
name: "gath"
__proto__: Object
Replace
JSON.parse("[{"name":"gath","age":10}]");
With
JSON.parse('[{"name":"gath","age":10}]');

Categories

Resources