JavaScript parse nested string to JSON.parse() - javascript

am facing an issue related to Json parsing in JavaScript. I have a string like below which I need to parse inside JSON.parse()
let object = "{ "result": "resultValue", "content": "the content for the content key will "go" here" }"
Now, when am doing like JSON.parse(object)
It throws an error Unexpected token , at some index, because of nested double quotes in content value, could you please suggest how can I parse these type of string to json , thanks in advance.

Change the quotes around the JSON to single quotes, so they don't conflict with the double quotes inside the JSON. And escape the quotes around "go" inside the content string.
If you create the JSON with a proper JSON encoder (e.g. JSON.stringify() in Javascript, json_encode() in PHP) you shouldn't have problems like this.
let object = '{ "result": "resultValue", "content": "the content for the content key will \\"go\\" here" }'
console.log(JSON.parse(object));

Related

JSON breaking with quotes

I am getting a Broken JSON, with quotes inside quotes. I can't convert it, because of the error;
{
"PENDENCIA": "Whatever",
"RESULTADO": "Teste "blabla"."
}
What you're looking for is how to "escape" characters in JSON. Because JSON uses quotes around all of the string values ("Whatever"), you can't just include a quote inside your string -- there's no way JSON can figure out that "Teste " isn't the full string but instead should be continued until the final ".
You will need to rewrite the JSON to be "Teste \"blabla\"."
If the JSON is being automatically generated, you'll need to fix whatever is generating your JSON.

browser appends escape \ character to javascript object

I am trying to send an MQTT message to topic from angular app which accepts the message in a specific syntax as follows
{
"Message": "hello" //the space after : is mandatory
}
but after I send the message in the above format the browser appends \ to the above code as follows
"{ \"Message\" : \"hello\" }"
which disrupts the actual syntax and the message is not accepted by the topic (receiver).
How can I fix this?
but once I hit send the browser appends \ to the above code as follows
What do you mean by "hit send in browser"? How are you sending the MQTT message? Since you seem to be sending a JSON, have you tried to somehow add the following header to the request sending the object:
'Content-Type': 'application/json'
As to why your code sample returns an Array, that is because your str variable is actually an Array with a single string element. The correct way of parsing your string to a json object would be as follows:
var str ="{\"message\": \"hello\"}"
console.log(str)
console.log(JSON.parse(str))
Notice the lack of square brackets [] (thus a string and not an array). Also, since str is no longer an array, it no longer has a map method, so we just directly call JSON.parse on it.
Note that you could also use single quotes instead of double quotes when declaring strings in javascript, so you could also declare str as follows:
var str ='{"message": "hello"}'
This way you don't need to escape your quotes with backslashes.

Why does json.parse break? and how to fix it

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)

JSON Lint says it's valid but JSON.parse throws error

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}]"};

How do I replace double quotes with its escape?

var string = "{ "Name": ""Jack"" }"
I want to replace the double quotes with \" so that the variable becomes a valid JSON.
so, it should end up looking like this:
string = "{ "Name": \""Jack"\" }"
I know you can use the replace function but I'm not getting it to work.
Put a backslash in front of each double quote that should be escaped.
var string = "{\"Name\":\"\\\"Jack\\\"\"}"
However, your questions very much looks like an XY problem where you are trying to do something in the completely wrong way! You usually never have to deal with escaping etc. when JSON is involved.
Initially you probably have an object. Let's assume obj = {Name: "Jack"}. Now you apparently want to JSON-encode it. In JavaScript you use JSON.stringify(obj) for it, in PHP you'd do json_encode($obj). However, if you want to assign this to a JS variable, you can just put the encoded JSON right after obj =, like this. If you really have to put a JSON string somewhere, you can simply run the JSON encoder over the string again (that's how I created the string in this post):
JSON.stringify(JSON.stringify({Name: 'Jack'}))

Categories