I have to stringify some JS objects to save the text somewhere and I'd like to be able to copy the saved text manually afterwards and pass it via the console to a function which then parses the text to do something with the original object.
Unfortunately parsing pasted text seems to have problems with escaped double quotes since parsing always fails.
I have created a small snippet which illustrates my problem:
http://jsfiddle.net/wgwLcgz6/1/
var jsonStr = JSON.stringify({ arg1: 'some string "with quotes"' });
$('#out1').html(jsonStr); // {"arg1":"some string \"with quotes\""}
JSON.parse(jsonStr); // Works just fine
try {
// Copied the ouput of JSON.stringify manually and pasted it directly into
// the parse function...
JSON.parse('{"arg1":"some string \"with quotes\""}');
// We never get here since an exception is thrown
$('#out2').html('Parsed successfully');
} catch (ex) {
// SyntaxError: Unexpected token w
$('#out2').html(ex.toString());
}
I think I do understand why this is happening even though I can't explain it properly but I don't have any idea on how to circumvent this and would really appreciate some help and maybe deeper explanation.
One more thing: If I paste the stringified object {"arg1":"some string \"with quotes\""} into an online json parser like http://jsonlint.com/ it parses it just fine which I guess is because they use there own parser instead of the browsers built in ones...
You need to escape quotes and backslashes. Since you're using single quotes around a string with double quotes, you just have to escape the backslashes:
JSON.parse('{"arg1":"some string \\"with quotes\\""}');
Related
I think this is a basic question, but I can't understand the reason. in JSON, it's valid to has a special character like "asdfadf\tadfadf", but when try parse it, it's shown error.
eg. code:
let s = '{"adf":"asdf\tasdfdaf"}';
JSON.parse(s);
Error:
Uncaught SyntaxError: Bad control character in string literal in JSON at position 12
at JSON.parse (<anonymous>)
at <anonymous>:1:6
I need to understand what is the issue, and solution.
You have to take into account that \t will be involved in two parsing operations: first, when your string constant is parsed by JavaScript, and second, when you parse the JSON string with JSON.parse(). Thus you must use
let s = '{"adf":"asdf\\tasdfdaf"}';
If you don't, you'll get the error you're seeing from the actual tab character embedded in the string. JSON does not allow "control" characters to be embedded in strings.
Also, if the actual JSON content is being created in server-side code somehow, it's probably easier to skip building a string that you're immediately going to parse as JSON. Instead, have your code build a JavaScript object initializer directly:
let s = { "adf": "asdf\tasdfdaf" };
In your server environment there is likely to be a JSON tool that will allow you to take a data structure from PHP or Java or whatever and transform that to JSON, which will also work as JavaScript syntax.
let t = '{"adf":"asdf\\tasdfdaf"}';
var obj = JSON.parse(t)
console.log(obj)
I have the following data coming in from my server into my js code, from my server.
{"triggers": [{"message_type": "sms","recipients": "[\"+91xxxxxxxxx\",\"+91xxxxxxxxx\"]","message": "This is a test"}]}
My code parses the above json string in the following manner.
data = '{"triggers": [{"message_type": "sms","recipients": "[\"+91xxxxxxxx\",\"+91xxxxxxxx\"]","message": "This is a test"}]}'
parsed = JSON.parse(data);
This throws the following exception
Uncaught SyntaxError: Unexpected token + in JSON at position 54
at JSON.parse (<anonymous>)
at eval (eval at <anonymous> (entry.html:2), <anonymous>:1:6)
at entry.html:298
I did a little bit of further digging and found the source of the json string.
Here is where the string is coming in from my python code
data = {"recipients": "[\"+91xxxxxxxxx\",\"+91xxxxxxxx\"]"} # This data comes in from my database, and I can't do anything about what quotes are used.
javascript_supplied_data = json.dumps(data) #This data goes to the frontend via webhook
I tried putting the same data into a json view via this online viewer, and it didn't throw any error and displayed the data correctly.
What I can't understand is, I am doing a json.dumps in my python code, so the string response should be json parsable. So why does JSON.parse throw this error?
Is there something wrong with the json libraries at the python end or the javascript end, or am I too much of a noob?.
Please help me figure out what is causing this issue, and how to solve it.
NOTE: I don't have any control over the string that comes in from the server.
When you have valid JSON, but put it in a string literal, the escapes treated by the literal notation in JavaScript make the string different. The backslashes are interpreted as for escaping the next character.
So either you have to go through the string literal and double all the backslashes, or you can apply String.raw to the string literal as template string:
var data = String.raw`{"triggers": [{"message_type": "sms","recipients": "[\"+91xxxxxxxx\",\"+91xxxxxxxx\"]","message": "This is a test"}]}`;
var parsed = JSON.parse(data);
console.log(parsed);
Note however, that the JSON you posted at the start of your question is valid.
On the other hand, the error you get indicates that the \" just before the first + is interpreted as just ". This means the \ is not actually there when the string is received from the server. This is usually caused by a similar escaping problem at the server side, where the programmer intended to send the backslash to the client, but actually just escaped the " on the server, which resulted in only the " being sent to the client and not \".
You have to use single quotes here while escape sequence.
if we use double quotes for escape sequence here it will result in
"recipients": "["+91xxxxxxxx","+91xxxxxxxx"]"
double quotes inside double quotes which is why your code breaks.
data = '{"triggers": [{"message_type": "sms","recipients": "[\'+91xxxxxxxx\',\'+91xxxxxxxx\']","message": "This is a test"}]}';
parsed = JSON.parse(data);
console.log(parsed)
I am facing some issues with escaping of back slash, below is the code snippet I have tried. Issues is how to assign a variable with escaped slash to another variable.
var s = 'domain\\username';
var options = {
user : ''
};
options.user = s;
console.log(s); // Output : domain\username - CORRECT
console.log(options); // Output : { user: 'domain\\username' } - WRONG
Why when I am printing options object both slashes are coming?
I had feeling that I am doing something really/badly wrong here, which may be basics.
Update:
When I am using this object options the value is passing as it is (with double slashes), and I am using this with my SOAP services, and getting 401 error due to invalid user property value.
But when I tried the same with PHP code using same user value its giving proper response, in PHP also we are escaping the value with two slashes.
When you console.log() an object, it is first converted to string using util.inspect(). util.inspect() formats string property values as literals (much like if you were to JSON.stringify(s)) to more easily/accurately display strings (that may contain control characters such as \n). In doing so, it has to escape certain characters in strings so that they are valid Javascript strings, which is why you see the backslash escaped as it is in your code.
The output is correct.
When you set the variable, the escaped backslash is interpreted into a single codepoint.
However, options is an object which, when logged, appears as a JSON blob. The backslash is re-escaped at this point, as this is the only way the backslash can appear validly as a string value within the JSON output.
If you re-read the JSON output from console.log(options) into javascript (using JSON.parse() or similar) and then output the user key, only one backslash will show.
(Following question edit:)
It is possible that for your data to be accepted by the SOAP consuming service, the data needs to be explicitly escaped in-band. In this case, you will need to double-escape it when assigning the value:
var s = 'domain\\\\user'
To definitively determine whether you need to do this or not, I'd suggest you put a proxy between your working PHP app and the SOAP app, and inspect the traffic.
I am parsing a JSON-string with the JQuery.parseJSON function, as I have done lot's of times in my code. On this particular case, though, I get: Uncaught SyntaxError: Unexpected token R. The only upper case R that exists, in my JSON-formatted String, comes right after an escaped quotation mark, ... \"R ... like this. It seems like too much of a coincidence to be caused by anything other than this, but as far as I can tell, I have completely followed the proper syntax as described on json.org.
EDIT:
I've tried to manually remove the occurrances of \" in a hardcoded test, and the string formats perfectly into a proper Javascript object. In other words, my \" is definitely the problem here...
var myObject = $.parseJSON(myString);
EDIT 2:
the problematic area of my String is here displayed, both in working, and not working condition. first the problematic one:
{"lineID":33,"boxID":10,"title":"My text with the \"Ruining Part\""}
Then the working one:
{"lineID":33,"boxID":10,"title":"My text with the Ruining Part"}
Finally how i format my javabean object into JSON string.
String jsonObjectAsString = new Gson().toJson(myJavaBeanObject);
You probably need to escape the backslash in your string, if it is hardcoded, so that the final string that gets parsed has a single backslash followed by a double quote. Otherwise, the browser thinks you are trying to escape a double quote in your string, which does nothing.
So change your string to:
...\\"R...
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