Since the JSON format specifies that single quotes should not be escaped, most libraries (or even the native JSON parser) will fail if you have an escaped single quote in it. Now this usually is not a problem since most of the time you do an XHR that fetches some data formatted as JSON and you use the responseText which contains your JSON string that you can then parse, etc.
In this particular situation, I have a JSON string stored in a database as text... so the database contains something like {"property":"value"} and I want to output this as part of an HTML page created by the server so that the JavaScript code in that page looks something like this:
var x = '{"property":"value"}';
Now if the JSON string in the database contains a single quote like this:
{"property":"val'ue"}
Then I need to escape it or else I will never be able to use it as a string:
console.clear();
var obj = {prop:"val'ue"};
var str = JSON.stringify(obj);
console.log("JSON string is %s",str);
console.dir(JSON.parse(str)); //No problem here
//This obviously can't work since the string is closed and it causes an invalid script
//console.dir(JSON.parse('{prop:"val'ue"}'));
//so I need to escape it to use a literal JSON string
console.dir(JSON.parse('{"prop":"val\'ue"}'));
The question then is why {"prop":"val\'ue"} not considered a valid JSON string ?
In JavaScript - the string '{"prop":"val\'ue"}' is a correct way to encode the JSON as a string literal.
As the JavaScript interpreter reads the single-quoted string, it will convert the \' to '. The value of the string is {"prop":"val'ue"} which is valid JSON.
In order to create the invalid JSON string, you would have to write '{"prop":"val\\\'ue"}'
If I understand the question right, you are trying to generate JavaScript code that will set some variable to the decoded version of a JSON string you have stored in the database. So now you are encoding the string again, as the way to get this string into JavaScript is to use a string literal, passing it through JSON.parse(). You can probably rely on using the server side JSON encoder to encode the JSON string as a JavaScript string literal. For instance:
<?php $jsonString = '{"prop":"val\'ue"}'; ?>
var myJson = JSON.parse(<?php echo json_encode($jsonString) ?>);
// Prints out:
// var myJson = JSON.parse("{\"prop\":\"val'ue\"}");
// And results: Object - { prop: "val'ue"}
However, If you are 100% sure the JSON is going to be valid, and don't need the weight of the extra parsing / error checking - you could skip all that extra encoding and just write:
var myJson = <?php echo $jsonString; ?>
Remember, JSON is valid JavaScript syntax for defining objects after all!
According to jsonlint it is valid without escaping the single quote, so this is fine:
{"prop": "val'ue"}
But this is invalid:
{"prop":"val\'ue"}
According to json.org json:
is completely language independent but
uses conventions that are familiar to
programmers of the C-family of
languages, including C, C++, C#, Java,
JavaScript, Perl, Python, and many
others
So it is the language conventions in c-type languages regarding the reverse solidus (\) that means that your example is not valid.
You might try the following, however, it's ugly.
JSON.parse("{\"obj\":\"val'ue\"}");
Or just store the string to a var first. This should not store the literal backslash value and therefore the JSON parser should work.
var str = '{"obj" : "val\'ue"}';
JSON.parse(str);
Related
I've a string in JSON format. I'm trying to iterate it. I have validate the string whether its JSON or not. It is fine. But, when I try to iterate it, it throws me error .
Here is my
var string = '[{"id":7,"userId":"123","courseId":"C4","courseValue":"{\"color\": \"blue\",\"value\": \"#f00\"}"},{"id":8,"userId":"123","courseId":"C5","courseValue":"{\"color\": \"green\",\"value\": \"#f00\"}"}]';
Here is the fiddle
http://jsfiddle.net/hLkUz/40/
You have taken some JSON and wrapped ' around it to try to make it a JavaScript string literal.
Some characters have special meaning in JavaScript string literals (such as \ which starts an escape sequence). You have failed to escape them within the string.
Consequently, to take an example:
"{\"color\":…
… when parsed as part of the JavaScript string literal becomes:
"{"color":…
… which isn't valid JSON.
You need to escape the special characters for the JavaScript string literal.
Better yet, restructure your JSON so that it doesn't contain values which are encoded as JSON themselves. Use an object instead of a string containing JSON representing an object.
You are having unwanted double string in values. Corrected json string is here
var string = '[{"id":7,"userId":"123","courseId":"C4","courseValue":{\"color\": \"blue\",\"value\": \"#f00\"}},{"id":8,"userId":"123","courseId":"C5","courseValue":{\"color\": \"green\",\"value\": \"#f00\"}}]';
Try this:
var string = '[{"id":7,"userId":"123","courseId":"C4","courseValue":{"color": "blue","value": "#f00"}},{"id":8,"userId":"123","courseId":"C5","courseValue":{"color": "green","value": "#f00"}}]';
There's no need to wrap the object with " nor escape it.
What you need is this:
var string = '[{"id":7,"userId":"123","courseId":"C4","courseValue":{"color": "blue","value": "#f00"}},{"id":8,"userId":"123","courseId":"C5","courseValue":{"color": "green","value": "#f00"}}]';
Fiddle
I'm not sure if you intend to escape the JSON within courseValue. However it seems like the escaping of the nested objects is the problem. This works
http://jsbin.com/mekiwalidu/edit?js,console,output
var string = '[{"id":7,"userId":"123","courseId":"C4","courseValue":{"color": "blue","value": "#f00"}},{"id":8,"userId":"123","courseId":"C5","courseValue":{"color": "green","value": "#f00"}}]';
var obj = JSON.parse(string);
console.log(obj);
I am trying to make sure input from user is converted into a valid JSON string before submitted to server.
What I mean by 'Converting' is escaping characters such as '\n' and '"'.
Btw, I am taking user input from HTML textarea.
Converting user input to a valid JSON string is very important for me as it will be posted to the server and sent back to client in JSON format. (Invalid JSON string will make whole response invalid)
If User entered
Hello New World,
My Name is "Wonderful".
in HTML <textarea>,
var content = $("textarea").val();
content will contain new-line character and double quotes character.
It's not a problem for server and database to handle and store data.
My problem occurs when the server sends back the data posted by clients to them in JSON format as they were posted.
Let me clarify it further by giving some example of my server's response.
It's a JSON response and looks like this
{ "code": 0, "id": 1, "content": "USER_POSTED_CONTENT" }
If USER_POSTED_CONTENT contains new-line character '\n', double quotes or any characters that are must be escaped but not escaped, then it is no longer a valid JSON string and client's JavaScript engine cannot parse data.
So I am trying to make sure client is submitting valid JSON string.
This is what I came up with after doing some researches.
String.prototype.escapeForJson = function() {
return this
.replace(/\b/g, "")
.replace(/\f/g, "")
.replace(/\\/g, "\\")
.replace(/\"/g, "\\\"")
.replace(/\t/g, "\\t")
.replace(/\r/g, "\\r")
.replace(/\n/g, "\\n")
.replace(/\u2028/g, "\\u2028")
.replace(/\u2029/g, "\\u2029");
};
I use this function to escape all the characters that need to be escaped in order to create a valid JSON string.
var content = txt.val().escapeForJson();
$.ajax(
...
data:{ "content": content }
...
);
But then... it seems like str = JSON.stringify(str); does the same job!
However, after reading what JSON.stringify is really for, I am just confused. It says JSON.stringify is to convert JSON Object into string.
I am not really converting JSON Object to string.
So my question is...
Is it totally ok to use JSON.stringify to convert user input to valid JSON string object??
UPDATES:
JSON.stringify(content) worked good but it added double quotes in the beginning and in the end. And I had to manually remove it for my needs.
Yep, it is totally ok.
You do not need to re-invent what does exist already, and your code will be more useable for another developer.
EDIT:
You might want to use object instead a simple string because you would like to send some other information.
For example, you might want to send the content of another input which will be developed later.
You should not use stringify is the target browser is IE7 or lesser without adding json2.js.
I don't think JSON.stringify does what you need. Check the out the behavior when handling some of your cases:
JSON.stringify('\n\rhello\n')
*desired : "\\n\\rhello\\n"
*actual : "\n\rhello\n"
JSON.stringify('\b\rhello\n')
*desired : "\\rhello\\n"
*actual : "\b\rhello\n"
JSON.stringify('\b\f\b\f\b\f')
*desired : ""
*actual : ""\b\f\b\f\b\f""
The stringify function returns a valid JSON string. A valid JSON string does not require these characters to be escaped.
The question is... Do you just need valid JSON strings? Or do you need valid JSON strings AND escaped characters? If the former: use stringify, if the latter: use stringify, and then use your function on top of it.
Highly relevant: How to escape a JSON string containing newline characters using javascript?
Complexity. I don't know what say.
Take the urlencode function from your function list and kick it around a bit.
<?php
$textdata = $_POST['textdata'];
///// Try without this one line and json encoding tanks
$textdata = urlencode($textdata);
/******* textarea data slides into JSON string because JSON is designed to hold urlencoded strings ******/
$json_string = json_encode($textdata);
//////////// decode just for kicks and used decoded for the form
$mydata = json_decode($json_string, "true");
/// url decode
$mydata = urldecode($mydata['textdata']);
?>
<html>
<form action="" method="post">
<textarea name="textdata"><?php echo $mydata; ?></textarea>
<input type="submit">
</html>
Same thing can be done in Javascript to store textarea data in local storage. Again textarea will fail unless all the unix formatting is deal with. The answer is take urldecode/urlencode and kick it around.
I believe that urlencode on the server side will be a C wrapped function that iterates the char array once verses running a snippet of interpreted code.
The text area returned will be exactly what was entered with zero chance of upsetting a wyswyg editor or basic HTML5 textarea which could use a combination of HTML/CSS, DOS, Apple and Unix depending on what text is cut/pasted.
The down votes are hilarious and show an obvious lack of knowledge. You only need to ask yourself, if this data were file contents or some other array of lines, how would you pass this data in a URL? JSON.stringify is okay but url encoding works best in a client/server ajax.
I have simple JSON that I need to parse to object. Strangely it doesn't work even though if I copy and paste my JSON string to JSONLint (http://jsonlint.com/) it will show that it's valid.
var string = '{"token":"9eebcdc435686459c0e0faac854997f3","email":"201403050007950","id":"13","updated_at":"2014-03-05 10:34:51","messageguides":"[{\"name\":\"Un-named Messaging Guide 1\",\"pages\":[\"sustainabilitydirectors\",\"marketingnbusinessdevelopmentdirectors\"],\"date\":1394015692958}]"}';
var obj = JSON.parse(string); // Unexpected token n
console.log(obj);
The \ characters in the data are treated as JSON escape characters when you parse the raw JSON.
When you embed that JSON inside a JavaScript string, they are treated as JavaScript escape characters and not JSON escape characters.
You need to escape them as \\ when you express your JSON as a JavaScript string.
That said, you are usually better off just dropping the JSON in to the JavaScript as an object (or array) literal instead of embedding it in a string and then parsing it as a separate step.
var obj = {"token":"9eebcdc435686459c0e0faac854997f3","email":"201403050007950","id":"13","updated_at":"2014-03-05 10:34:51","messageguides":"[{\"name\":\"Un-named Messaging Guide 1\",\"pages\":[\"sustainabilitydirectors\",\"marketingnbusinessdevelopmentdirectors\"],\"date\":1394015692958}]"};
I am using Dojo.fromJson to convert json string to javascript object, but throw exception. Because, there are control characters such as ',\n,\r in the json string.
How can I solve this problem in dojo? convert json string to javascript object, even if there are control characters.
I use Newtonsoft.JsonConvert.SerializeObject to convert C# oject to json data. Json Object: {"name":"'\"abc\n123\r"} then, I use Dojo.fromJson(' {"name":"'\"abc\n123\r"}') to convert json data to javascript object.
Thank you very much!
Problem, i believe is the double-quote which should be escaped by triple backslashes. You can use "native browser JSON decode" as searchterm for "dojo fromJson" synonym.
Without knowing my way around C# - I havent tested but i believe following should work:
string c_sharp_name = "'\"abc\n123\r";
// C#Object.name
c_sharp_name = c_sharp_name.
replace('"', '\\"'). // maybe add a slash on serverside
replace('\n', '\\\n').
replace('\r', '\\\r');
since
while this fails:
{"name":"'\"abc\n123\r"} // your single backslash
this would work:
{"name":"'\\\"abc\\\n123\\\r"} // working triple backslash escape
I got a json structure somehow as below and my question is how can i parse this with jQuery so that i can use it like myJson[0].name and than alert it so that "M\\xe9t\\xe9o" = Météo.
Jquery tells me this is invalid json why ?
Json uses double backslash if i use single backslash ("M\xe9t\xe9o") Jquery is OK with the syntax.
var jsonObj = '{"title":[{"id":"1","name": "M\\xe9t\\xe9o"},{"id":"2","name": "Meteo"}]}';
var myJson = jQuery.parseJSON(jsonObj);
The JSON syntax only allows \uxxxx escapes.
Change it to "M\\u00e9t\\u00e9o".
If you use a single backslash, it gets parsed by the Javascript string literal, so the actual string value contains the real Unicode character, not an escape. In other words, "M\xe9t\xe9o" === "Météo"
It is looks like the json was incorrectly (manually?) encoded. When you encode it in UTF-8, e.g. with PHP, you'll get:
{"title":[{"id":"1","name": "M\u00e9t\u00e9o"},{"id":"2","name": "Meteo"}]}
which is correctly parsed by JS. But \xe9 is unrecognized by parser.