How do JSON.parse() and escape characters work in JavaScript? - javascript

Suppose I have an object variable:
var obj = {
key: '\"Hello World\"'
}
Then I tried parse it to string by using JSON.stringify in Chrome devtools console:
JSON.stringify(obj) // "{"key":"\"Hello World\""}"
I get the result "{"key":"\"Hello World\""}". Then I give it to a string
var str = '{"key":"\"Hello World\""}'
At least I try to convert it back to obj:
JSON.parse(str);
but the browser tell me wrong Uncaught SyntaxError
What confused me is why this is wrong? I get the string from an origin object and I just want turn it back.
How can I fix this problem? If I want do the job like convert obj to string and return it back, how can I do?

You're tried to convert your JSON into a string literal by wrapping it in ' characters, but \ characters have special meaning inside JavaScript string literals and \" gets converted to " by the JavaScript parser before it reaches the JSON parser.
You need to escape the \ characters too.
var str = '{"key":"\\"Hello World\\""}'
That said, in general, it is better to not try to embed JSON in JavaScript string literals only to parse them with JSON.parse in the first place. JSON syntax is a subset of JavaScript so you can use it directly.
var result = {"key":"\"Hello World\""};

try:
var str = '{"key":"\\"Hello World\\""}';

Related

Why JSON.parse fails with this array-like string

I tried to JSON parse this
let string = `["\"test1, "\"test2"]`;
let array = JSON.parse(string);
console.log(array[0]);
It's fairly simple enough but I don't understand what's error message is supposed to tell
Uncaught SyntaxError: Unexpected token t in JSON at position 3
you are using template string to create a string.
it doesnt need a escape character for double quotes ".
type this:
let string = `["test1", "test2"]`;
let array = JSON.parse(string);
console.log(array[0])
you need a escape character for " only when you are using normal string. like this:
let string = "[\"test1\", \"test2\"]";
let array = JSON.parse(string);
console.log(array[0])
im not good at english.hope useful

JavaScript json.parse string error

I want to parse this string to an array
var string= "['one','two']";
var result= JSON.parse(string);
It throws an error
`Unexpected token ' in JSON at position 1'
I believe my approach is right I just can't figure out why its throwing that error.
You should use double quotes:
var string = '["one", "two"]';
You can't use single quote in a JSON string.
Just make it like this
var string= '["one","two"]';
var result= JSON.parse(string);
Json standard requires that the string have double quotes inside.

JSON.stringify / parse oddness with quote marks

I am running into an odd little problem with parsing some JSON which has quotes in it. I am using the native JSON.stringify and JSON.parse functions to do this. If I stringify an object which an object which has quote marks in it, they are escaped as one would expect. If I then parse this back into an object, it again works fine.
The problem is occurring where I stringify, then print the object to a page, then parse the resulting string. If I try to do this, the parse function fails as stringify has only put single slashes before each of the offending quote marks.
The reason I need to achieve this is I am working on an application that dynamically loads content stored in a database as JSON strings. The strings at some point need to be printed onto the page somewhere so that the javascript can find them and build the page based on their contents. I need some way of robustly passing the object into and out of strings which will not fail if a user inputs the wrong characters!
I can solve this for the moment by inserting extra slashes into the code with a replace call, but I was wondering if there is a better way to handle this?
I have put together a couple of jsfiddles to illustrate what I am trying to describe:
http://jsfiddle.net/qwUAJ/ (Stringify then parse back)
var ob = {};
ob["number1"] = 'Number "1"';
ob["number2"] = 'Number 2';
ob["number3"] = 'Number 3';
var string = JSON.stringify(ob);
var reOb = JSON.parse('{"number1":"Number \"1\"","number2":"Number 2","number3":"Number 3"}');
$('div').html(string);
http://jsfiddle.net/a3gBf/4/ (Stringify, then print, then parse back)
// Make an object
var ob = {};
ob["number1"] = 'Number "1"';
ob["number2"] = 'Number 2';
ob["number3"] = 'Number 3';
// Turn the object into a JSON string
var string = JSON.stringify(ob);
// Printing the string outputs
// {"number1":"Number \"1\"","number2":"Number 2","number3":"Number 3"}
$('.stringified').html(string);
// Attempt to turn the printed string back into an object
var reOb = JSON.parse('{"number1":"Number \"1\"","number2":"Number 2","number3":"Number 3"}');
// This fails due to the single escaped quote marks.
Thank you for any help in advance!
This is a problem which arises from re-evaluating a String without first converting it back into a string literal, so the meaning changes if it is even still valid.
You need to consider what does '\"' as a literal actually mean? The answer is ", without the \. Why?
\" resolves to "
If you want to have \" as the result of the literal, you need to write '\\\"'
\\ resolves to \
\" resolves to "
So basically, the extra slashes are required to escape any characters with special meaning in string literals.
If you did var reOb = JSON.parse($('.stringified').html()); it would work fine as is.
Consider further
str = '\\\"\\\''; // \"\'
str = '\"\''; // "'
str = '"''; // SyntaxError: Unexpected token ILLEGAL
As far as I'm aware, JavaScript offers no native implementation to convert strings as desired, so the easiest method I know of is using a replace
function toLiteral(str) {
var dict = {'\b': 'b', '\t': 't', '\n': 'n', '\v': 'v', '\f': 'f', '\r': 'r'};
return str.replace(/([\\'"\b\t\n\v\f\r])/g, function ($0, $1) {
return '\\' + (dict[$1] || $1);
});
}
toLiteral('foo\\bar'); // "foo\\bar"
If you generate JS with PHP code you should escape the quotes in your JSON string:
//PHP code generating js code
echo "var myJSONString = \"". str_replace("\"","\\\"",$mySqlJSON)."\";";

Convert array formatted strings to object

I got
[[["汽車","car","Qìchē",""]],[["名詞",["汽車","車","轎車","車輛","車廂"],[["汽車",["car","automobile","auto"],,0.26497361],["車",["car","vehicle","lathe","machine","rook","turn"],,0.21967085],["轎車",["car","bus"],,0.020115795],["車輛",["vehicle","car"],,0.013611027],["車廂",["car"],,0.0042828997]]]],"en",,[["汽車",[4],0,0,1000,0,1,0]],[["car",4,[["汽車",1000,0,0],["車",0,0,0],["轎車",0,0,0],["車輛",0,0,0],["車廂",0,0,0]],[[0,3]],"car"]],,,[["en"]],27]
this from google translator
However I tried
JSON.parse(xhr.responseText);
It return an error Unexpected token
The problem is that this string contains multiple commas making your json invalid.
You could try to replace it for a single one before parsing
var x = '[[["汽車","car","Qìchē",""]],[["名詞",["汽車","車","轎車","車輛","車廂"],[["汽車",["car","automobile","auto"],,0.26497361],["車",["car","vehicle","lathe","machine","rook","turn"],,0.21967085],["轎車",["car","bus"],,0.020115795],["車輛",["vehicle","car"],,0.013611027],["車廂",["car"],,0.0042828997]]]],"en",,[["汽車",[4],0,0,1000,0,1,0]],[["car",4,[["汽車",1000,0,0],["車",0,0,0],["轎車",0,0,0],["車輛",0,0,0],["車廂",0,0,0]],[[0,3]],"car"]],,,[["en"]],27]'
.replace(/,{2,}/g, ",") // 2 or more replace for 1
JSON.parse(x);
Or if you have access to whatever is sending this string fix the output.
First you should remove an extra [] brackets by replacing that.
ex,
[["汽車","car","Qìchē",""]]
should be:
["汽車","car","Qìchē",""]
EDIT: you can refer to this answer: Parse Google Translate Json C#
You should try:
var str = '[[["汽車","car","Qìchē",""]],[["名詞",["汽車","車","轎車","車輛","車廂"],[["汽車",["car","automobile","auto"],,0.26497361],["車",["car","vehicle","lathe","machine","rook","turn"],,0.21967085],["轎車",["car","bus"],,0.020115795],["車輛",["vehicle","car"],,0.013611027],["車廂",["car"],,0.0042828997]]]],"en",,[["汽車",[4],0,0,1000,0,1,0]],[["car",4,[["汽車",1000,0,0],["車",0,0,0],["轎車",0,0,0],["車輛",0,0,0],["車廂",0,0,0]],[[0,3]],"car"]],,,[["en"]],27]';
var objstr = $.parseJSON(str);

JSON.stringify escapes double quotes every time when stringified

I am storing JSON objects retreived from web service to objects in javascript. In many places this gets stringified(This obj goes through some plugins and it strigifies and stores it and retreives it) and it adds multiple slashes. How can I avoid it ?
http://jsfiddle.net/MJDYv/2/
var obj = {"a":"b", "c":["1", "2", "3"]};
var s = "";
console.log(obj);
s = JSON.stringify(obj);
alert(s); // Proper String
s = JSON.stringify(s);
alert(s); // Extra slash added, Quotes are escaped
s = JSON.stringify(s);
alert(s); // Again quotes escaped or slash escaped but one more slash gets added
var obj2 = JSON.parse(s);
console.log(obj2); // Still a String with one less slash, not a JSON object !
So when parsing this multiple string I end up with a string again. And when tried to access like an object it crashes.
I tried to remove slash by using replace(/\\/g,"") but I end with this : ""{"a":"b","c":["1","2","3"]}""
What did you expect to happen?
JSON.stringify does not act like an "identity" function when called on data that has already been converted to JSON. By design, it will escape quote marks, backslashes, etc.
You need to call JSON.parse() exactly as many times as you called JSON.stringify() to get back the same object you put in.
Try
JSON.stringify(s).replace(/\\"/g, '"')
You can avoid that simply by calling JSON.stringify() exactly once on the data you want turn into JSON.
Try this:
s = {"a":"b", "c":["1", "2", "3"]}
JSON.stringify(JSON.stringify(s))
gives the output as
'"{\"a\":\"b\",\"c\":[\"1\",\"2\",\"3\"]}"'

Categories

Resources