JSON.parse error when in text is present \' or \" - javascript

In PHP I use mysql_real_escape_string that transforms symbol ``' and " to \' and \"
After, I extract data from MySQL and use it in JavaScript as JSON.
For example, the b' is transformed to b\' , and in JavaScript I have these errors:
var a='{"a":"b\'"}';
var b=JSON.parse(a);
alert(b.a);
var a='{"a":"b\""}';
var b=JSON.parse(a);
alert(b.a);
/*
Exception: JSON.parse: expected ',' or '}' after property value in object at line 1 column 9 of the JSON data
*/

If you are looking to include the quote in the JSON String, add an addition \.
Example
var a = '{"a":"b\'"}';
var b = JSON.parse(a);
alert(b.a);
var a = '{"a":"b\\""}';
var b = JSON.parse(a);
alert(b.a);

Remove extra quote from this line var a='{"a":"b\""}';
Modified Code:
var a='{"a":"b\"}';
var b=JSON.parse(a);
alert(b.a);

var a='{"a":"b\'"}'; //or you can use "{\"a\":\"b'\"}";
var b=JSON.parse(a);
alert(b.a);
This works because the value stored in variable a is {"a":"b'"}
var a='{"a":"b\\""}'; //or you can use "{\"a\":\"b\\\"\"}";
var b=JSON.parse(a);
alert(b.a);
For this case the value stored in variable a is {"a":"b\""}
You can try to construct the string that the JSON should look like by constructing the object and stringify it like so:
var a = { "a" : "b'" };
console.log(JSON.stringify(a));

After you extract data from MySQL, use stripslashes() to strip the extra backslashes. And then encode the data as JSON.

Related

How should a JSON string with quotes inside can be parsed with javascript

var str = '{"Language":"en","Type":"General","Text":""Mela" means "apple" in Italian"}';
Now JSON.parse(str) throws this error
Uncaught SyntaxError: Unexpected token M in JSON at position 43
Now replacing quotes escapes whole string and parsed JSON is not usable anymore
str = str.replace(/\\([\s\S])|(")/g,"\\$1$2");
"{\"Language\":\"en\",\"Type\":\"General\",\"Text\":\"\"Mela\" means \"apple\" in Italian\"}"
Other solutions like below do not seem to be working in this scenario
How to escape a JSON string containing newline characters using JavaScript?
You need to add a backslash before each double quote within your string as:
const str = '{"Language":"en","Type":"General","Text": "\\"Mela\\" means \\"apple\\" in Italian"}';
const obj = JSON.parse(str)
console.log(obj.Text)
In JSON you don't escape double quotes of the property name or the begging of the property value, just escape what's inside property value:
{\"Text\":\"\"Mela\" means ....
It should be like this:
{"Text":"\"Mela\" means ....
This can be done with multiple replacements:
var str = '{"Language":"en","Type":"General","Text":""Mela" means "apple" in Italian"}';
str = str.replace(/"/,"'"); //Replace all " with '
str = str.replace(/{'/,'{"') //Restore " to start of JSON
str = str.replace(/','/,'","'); //Restore " around JSON , separators
str = str.replace(/':'/,'":"'); //Restore " around JSON : separators
str = str.replace(/'}/,'"}'); //Restore " to end of JSON
str = str.replace(/'/,'\"'); //All remaining ' must be inside of data, so replace with properly escaped \"
console.log(str);
EDIT: A problem with this solution is that is will also replace original ' characters with " inside the text.

Split object in Node.js

Yesterday i solve my problem spliting my string with "\" but today i have the same problem but with a object...
2|wscontro | [2017-05-31 15:57:23.145] - debug: /opt/wscontroller/wscontroller-api/routes/ubus UbusController 63320169-611e-43f5-880e-9b1a13152cfd getDeviceServicesById signature {"config":"wireless","section":"radio0","values":"{\"disabled\":0}"}
2|wscontro | [2017-05-31 15:57:23.145] - debug: /opt/wscontroller/wscontroller-api/routes/ubus UbusController 63320169-611e-43f5-880e-9b1a13152cfd getDeviceServicesById signature "object"
I need to have only signature =>
{"config":"wireless","section":"radio0","values":{"disabled":0"}}
Can anyone help me? I try to convert to String this object and split doing
var aux = signature.split('\\').join('');
var jsonObject = JSON.parse(aux);
But i get the same result {"config":"wireless","section":"radio0","values":"{\"disabled\":0"}}
My last post: Split string by "\" Node.js
anyone can help?
is this you wanted?
var str =' {"config":"wireless","section":"radio0","values":"{\"disabled\":0"}';
console.log(str.replace(/\\/g,''));
Your object should be like you said in your last comment {"config":"wireless","section":"radio0","values":"{\"disable‌​d\":0}"} then:
var jsonstring = "{"config":"wireless","section":"radio0","values":"{\"disable‌​d\":0}"}";
var escapedJsonstring = jsonstring.split('\\').join('');
var json = JSON.parse(escapedJsonstring);
json.parsedValues = JSON.parse(json.values);
console.log(json);
Finally you have parsed object in json variable. The main idea is that the values attribute has also string value and not object value. So you need to parse it again as JSON. Result of this parsing is stored in json.parsedValues, but you can rewrite the values string with object using this: json.values = JSON.parse(json.values);

Replace double quotes with backslash plus double quotes within JSON

Suppose I have this simple JSON:
{"test":"test"}
Now I want to convert it into the following format:
{\"test\":\"test\"}
I have found some of the solutions of replacing double quotes with backslash and double quotes but all those works on text format.
I need to pass this kind of format to AWS SNS as message parameter.
As I suggested in comment
You can go from a Javascript object to an escaped JSON using JSON.stringify twice
var myObject = {"test":"test"};
var myJson = JSON.stringify(myObject); // {"test":"test"}
var myEscapedJson = JSON.stringify(myJson); // "{\"test\":\"test\"}"
You may convert the JSON object to a string format first by using JSON.stringify()
var temp = {"test":"test"};
var tempStr = JSON.stringify(temp);
console.log(tempStr); //> {"test":"test"}
var modifiedStr = tempStr.replace(/"/g, '\\"');
console.log(modifiedStr); //> {\"test\":\"test\"}
If your want to just encode only the open and close double quote, you may try this
var temp = {"test":'te"st'};
var tempObj = JSON.parse(JSON.stringify(temp));
for(var k in tempObj){
tempObj[k]=tempObj[k].replace(/"/g, "<DOUBLE_QUOTES_4594>");
}
var tempStr = JSON.stringify(tempObj);
console.log(tempStr); //> {"test":"te<DOUBLE_QUOTES_4594>st"}
var modifiedStr = tempStr.replace(/"|"/g, '\\"').replace(/<DOUBLE_QUOTES_4594>/g, '"');
console.log(modifiedStr); //> {\"test\":\"te"st\"}

How can we split a string with out quotes using jQuery or Javascript

I have a string coming from database like Agree,don't,partially,completely. without quotes. I have taken this in to a variable and I have splitted.
var x= Agree,Dont,Partially,completely;
var split = x.split(',');
but the code is not working then i have inserted the quotes to the string like.
var x = "\'" + answer coming from database + "\'";
var split = x.split(',');
Then the code works out but i get the ans as
x[0] = "Agree,x[1]=Dont ... x[3] = Completely"
My question is how can i split the value without appending the quotes to the x.
Hope you understand my question
Reagrds,
Sri
var x= "Agree,Dont,Partially,completely";
var split = x.split(',');
alert(split[0]+" "+split[1]);
Your syntax should be:
var x = 'Agree,Dont,Partially,completely';
var split = x.split(',');
The quotation marks define the start and end of the string above.
var x= "Agree,Dont,Partially,completely";
var split = x.split(',');
This should give what you need

String replace not working?

I've been trying to replace to following string using the following...
var r = response.replace('var s = getService().getValue(\"join\")', 'null');
However, the String remains un changed and I can't understand why. The String itself takes the following format..
{"r":[],"c":true,"c":{"tags":
[],"":3023,"s":".src.util.S#6f4e9e57","class":"class
src.util.dtos.DTO","Type":"public","c":"m","s":0,"de
fault":false,"id":544,"d":"","n":4,"na":"S","tagString":"","Pages":5},"results":[],"q":"","msg":"var
s = getService().getValue(\"join\")
The actual string itself is a little longer but I hope you get the idea from that abstract.
If your
var s = getService().getValue(\"join\")
part is a JavaScript code inside a JSON string, then you need to quote them again before replacing.
var r = response.replace('var s = getService().getValue(\\"join\\")', 'null');
It's because the double quotes escaped in JSON are not supposed to be escaped inside a single-quoted string.
So, instead of:
var r = response.replace('var joinstakqueries = getService().getValue(\"join\")', 'null');
try:
var r = response.replace('var joinstakqueries = getService().getValue("join")', 'null');

Categories

Resources