Replace double quotes with backslash plus double quotes within JSON - javascript

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\"}

Related

How Can I convert this complex a string into JSON with "" in key values?

I am trying to convert a string to json.
var str = "[{Value:0.64,Rate:Hourly,Description:Hourly if more than 50 hours,Upper Limit:null},{Value:1.68,Rate:Hourly,Description:Hourly if less than 400 hours,Upper Limit:500}]"
I tried with stringify and parse but that didn't work.
I tried with below function :
function getJsonData(query){
let arrayOfKeyValues = query.split(',');
let modifiedArray = new Array();
console.log(arrayOfKeyValues);
for(let i=0;i< arrayOfKeyValues.length;i++){
let arrayValues = arrayOfKeyValues[i].split(':');
let arrayString ='"'+arrayValues[0]+'"'+':'+'"'+arrayValues[1]+'"';
modifiedArray.push(arrayString);
}
let jsonDataString = '{'+modifiedArray.toString()+'}';
let jsonData = JSON.parse(jsonDataString);
console.log(jsonData);
console.log(typeof jsonData);
return jsonData;
}
Is there a way to use regex or this function to get the expected output with double quotes ("") added
to each key value?
I have to as least make the assumption that your KEYS all do not contain a comma.
Because, say you have:
{a:b,c,d:e}
It is ambiguous whether it should be: {a:"b","c,d":"e"} or {a:"b,c",d:"e"}
Just for simplicity, I am also assuming there is no {, }, : characters in your key or value...
The expression is:
JSON.parse(
str
.replace(new RegExp('{','g'),'{"')
.replace(new RegExp('}','g'),'"}')
.replace(new RegExp(':','g'),'":"')
.replace(new RegExp(',([^{][^,]*:)','g'),'","$1')
)
This will be the outcome:
var str = "[{Value:0.64,Rate:Hourly,Description:Hourly if more than 50 hours,Upper Limit:null},{Value:1.68,Rate:Hourly,Description:Hourly if less than 400 hours,Upper Limit:500}]"
const regStr = str
.replace(/:/g,'":"')
.replace(/,/g,'","')
.replace(/}","{/g,'"},{"')
.replace(/^\[{/,'[{"')
.replace(/}]$/, '"}]')
jsonResult = JSON.parse(regStr)
console.log(jsonResult);

How to convert array defined in string variable with \r\n using Javascript?

I have a string variable with array data .
var str = "[\r\n  10,\r\n  20\r\n]" ;
I want to convert above string to array like using javascript .
Output :-
var arr = [10,20];
You can simply use JSON.parse - it will ignore the newlines and convert the string representation of an array to a JavaScript array:
var str = "[\r\n 10,\r\n 20\r\n]" ;
var arr = JSON.parse(str);
console.log(Array.isArray(arr))
console.log(arr)
You need only to parse that string as a JSON, because it is clearly an array.
So this is the procedure:
var str = "[\r\n 10,\r\n 20\r\n]";
const myArray = JSON.parse(str);
console.log(myArray);
UPDATE:
If you are wondering why those special chars (\r\n) are going away:
// a string
const str = "[\r\n 10,\r\n 20\r\n]";
// if I print out this, Javascript, will automatically replace those special
// chars with what they means (new line)
console.log(str);
console.log(typeof(str));
// so if we are going to parse our string to the JSON parser
// it will automatically transform the special chars to new lines
// and then convert the result string "[10,20]" to an array.
const myArray = JSON.parse(str);
console.log(myArray);
console.log(typeof(myArray));

Converting int array in string format to array

I have an array of integers stored in string format.
eg:
"[3,2,1]"
How can I convert this to an actual array?
I've searched high and low for a simple solution but I can't seem to find it.
Passing the string into JSON.parse and $.parseJSON results in "[" being shown for the 0 index. So I'm assuming it's not doing anything.
var arr = JSON.parse("[3,2,1]")
var text = "[3,2,1]";
var obj = JSON.parse(text);
console.log(obj);
You could use jQuery $.parseJSON() method :
var arr = $.parseJSON("[3,2,1]");
var str = "[3,2,1]";
console.log( $.parseJSON(str) );
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
Or pure javascript method JSON.parse() :
var arr = JSON.parse("[3,2,1]");
Hope this helps.
var str = "[3,2,1]";
console.log( JSON.parse("[3,2,1]") );
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
So I've figured out I needed to slice the first and last characters off as for some reason the string was being returned as ""[3,2,1]"" rather than "[3,2,1]" even though it's stored without quotes.
From your updated description it appears you have a string that starts and ends with ", so a simple JSON.parse will not work, since that will just convert what's between the "'s to a string. You need to either JSON.parse twice, since you have an array of integers embedded in a string, or manually parse.
JSON.parse twice way:
var str = '"[3,2,1]"';
var parsedStr = JSON.parse(str); // results in a string with contents [3,2,1]
var intArray = JSON.parse(parsedStr); // results in an int array with contents [3,2,1]
Or, if format could change to be non-JSON at some point, manual way:
var str = '"[3,2,1]"';
var intArray = [];
str.substr(2,str.length-3).split(/,/g).forEach(function(numStr) {
intArray.push(parseInt(numStr));
});

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

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.

Remove quotes from array beginning & trailing

How to remove the leading & trailing double quotes outside the array.
var data = [{"name":"myName" ,"address": "myAddress" }];
alert(data[0].name)
If you want to convert a string representation of JSON data into an Javascript object:
http://jsfiddle.net/H2yN6/191/
var str = "[{\"name\":\"myName\" ,\"address\": \"myAddress\" }]";
var data = JSON.parse(str);
alert(data[0].name);
But if you really do want to remove some leading and/or trailing characters, you can use substring():
http://jsfiddle.net/H2yN6/193/
var str = "\"[{\"name\":\"myName\" ,\"address\": \"myAddress\" }]\"";
var str2 = str.substring(1, str.length - 1);
alert(str2);

Categories

Resources