Javascript JSON.stringify change my string that contains backslash - javascript

I have this string variable
iteration = "Toolset\\Iteration 1"
But when I add the string to a JSON.stringify it changes the value adding two more backslashes Toolset\\\\Iteration 1
var data = JSON.stringify([
{
"op": "add",
"path": "/fields/System.IterationPath",
"value": iteration
}
]);
//output: Toolset\\\\Iteration 1
I need the output to be Toolset\\Iteration 1
What is the best way of adding that particular string with 2 backslashes to a JSON variable?

JSON stringify encodes the object into a string. The actual value of the JSON is seen after you decode it from the string. The fact that the stringified version has escaped your slashes won't affect the actual value after the decode.

Related

Adding quotation makes to JSON String which contains some XML values

I'm trying to format a JSON input string in Javascript so that I can use it as a map.
{accountNumber:E22E6178D16777E1E053020011AC64B0,paymentMethodObject:<ns2:Token>123</ns2:Token><ns2:Type>CreditCard</ns2:Type>,preview:true}
To do this I need to put quotation marks around each key and value. Like here:
{
"accountNumber": "12345",
"paymentMethodObject": "<ns2:Token>123</ns2:Token><ns2:Type>CreditCard</ns2:Type>",
"preview": "true"
}
The problem is when I try to do it, quotes get added to the XML values also because they also contain a colon.
Maybe you need to use method replace with pattern Regex that match key:value replace it with surrounded by quotes pair!
let strJSON = '{accountNumber:E22E6178D16777E1E053020011AC64B0,paymentMethodObject:<ns2:Token>123</ns2:Token><ns2:Type>CreditCard</ns2:Type>,preview:true}';
let objJSON = strJSON.replace(/(\w+):([\/<>:\w+]+)/g,'"$1":"$2"');
console.log(objJSON)

JSON Array exception using json string field

I am trying to create a JSONArray object and in the JSONArray there is another array which contains an object that is a json string as below. Note the res field.
[{
"time": 123813213,
"value": [{
"name": "task",
"res": "{\"taskName\" : \"NAME\", \"taskValue\" : 3}"
}]
}]
This causes an exception when I return the above as a String and do
String jsonStr = "[{ \"time\": 123813213, \"value\": [{ \"name\": \"task\", \"res\": \"{\"taskName\", \"taskValue\"}\" }] }]";
JSONArray jsonArr = new JSONArray(jsonStr);
The problem is fixed when I do this by adding additional \ where the json string that I am storing is located.
String jsonStr = "[{ \"time\": 123813213, \"value\": [{ \"name\": \"task\", \"res\": \"{\\\"taskName\\\", \\\"taskValue\"}\\\" }] }]";
JSONArray jsonArr = new JSONArray(jsonStr);
Note the additional \ that I added. I am not sure how to fix the first case as I am not creating the jsonStr myself but instead getting it from somewhere and it only contains one \ not three \. Is there something I am doing wrong in the first case?
The exception I get is this using the first example
org.json.JSONException: Expected a ',' or '}' at 61 [character 62 line 1]
at org.json.JSONTokener.syntaxError(JSONTokener.java:432)
at org.json.JSONObject.<init>(JSONObject.java:223)
at org.json.JSONTokener.nextValue(JSONTokener.java:362)
at org.json.JSONArray.<init>(JSONArray.java:117)
at org.json.JSONTokener.nextValue(JSONTokener.java:365)
at org.json.JSONObject.<init>(JSONObject.java:208)
at org.json.JSONTokener.nextValue(JSONTokener.java:362)
at org.json.JSONArray.<init>(JSONArray.java:117)
at org.json.JSONArray.<init>(JSONArray.java:145)
at Main.main(Main.java:10)
The second example parses fine and returns the correct result which is this.
[{"time":123813213,"value":[{"res":"{\"taskName\", \"taskValue\"}","name":"task"}]}]
Question is how do I get the first example to return this?
The first case should be fine. Since you're getting it from an external source you don't have to add extra backslashes to escape characters. But when you manually type out a string literal in your code it requires adding backslashes to escape certain characters.
Note that "{\"taskName\", \"taskValue\"}" is invalid JSON. If it could be parsed it would result in {"taskName", "taskValue"} which isn't valid syntax in javascript. To create an array you would use ["taskName", "taskValue"].
If you meant for it to be an object it would be something like {"taskName": "Wash dishes", "taskValue": 5}
Please share the exception. It is a valid JSON, it should work.
The second one is working because when you convert a JSON to a String in JAVA it is created as this.
"[{\"time\":123813213,\"value\":[{\"name\":\"task\",\"res\":\"{\\"taskName\\" : \\"NAME\\", \\"taskValue\\" : 3}\"}]}]"
You can try this by using any JSON to String converter in java.
There is nothing wrong with your json.

Parse JSON like string by javascript

I have this variable which is json-like string, error appear while parse to a object
"SyntaxError: JSON.parse: expected ',' or '}' after property value in object"
Code:
var obj = JSON.parse('{"data":[{"from":"{\"category\":\"Bank/financial institution\"}"}],"statusCode":200}');
Seems the function not available for nested "{\"category\":\"Bank/financial institution\"}", replace with simple text (e.g. "123") would be fine, is there any way to handle such cases? Thanks.
The \ (backslash) character before "category is unnecessary.
There's no need to escape a double quote in a single-quoted string.
Your string is indeed malformed.
You either want:
var obj = JSON.parse('{"data":[{"from":{"category":"Bank/financial institution"}}],"statusCode":200}');
...(e.g., without quotes around the value of from and without backslashes) which when deserialized results in an object with a property called data which is an array, which has as its first entry an object with a property called from which is an object: Live Example | Source
or
var obj = JSON.parse('{"data":[{"from":"{\\"category\\":\\"Bank/financial institution\\"}"}],"statusCode":200}');
...(e.g., keeping the quotes around the value for from and making sure the backslashes appear in the JSON, which means escaping them) which is the same until you get to from, which is a string: Live Example | Source
Remove quots for inner object
var obj = {
"data": [{
"from": {
"category": "Bank/financial institution"
}
}],
"statusCode": 200
}

JSON.stringify escaping without need

JSON.stringify is converting my json object to the following string
{\"2003\":{\"1\":{\"2\":[\"test\"],\"3\":[\"test2\"]}}}
When it should not be escaped. The result should be as the string quoted below
{"2003":{"1":{"2":["test"],"3":["test2"]}}}
Rather than use a general replace of all the escaped quotes and remove ones that could be in the input. How can I set JSON.stringify to not double escape the variables?
You are stringifying a string, not an object:
var str = '{"2003":{"1":{"2":["test"],"3":["test2"]}}}';
var obj = {"2003":{"1":{"2":["test"],"3":["test2"]}}};
console.log( JSON.stringify(str) ); // {\"2003\":{\"1\":{\"2\":[\"test\"],\"3\":[\"test2\"]}}}
console.log( JSON.stringify(obj) ); // {"2003":{"1":{"2":["test"],"3":["test2"]}}}
Try these two examples in browser`s console:
let obj = {2003:{1:{2:["test"],3:["test2"]}}};
JSON.stringify(obj);
-> "{\"2003\":{\"1\":{\"2\":[\"test\"],\"3\":[\"test2\"]}}}"
and
let obj = {2003:{1:{2:["test"],3:["test2"]}}};
console.log(JSON.stringify(obj));
-> {"2003":{"1":{"2":["test"],"3":["test2"]}}}
In both cases the string returned from JSON.stringify is valid
In the first case you print "raw" string to console which starts and ends with double quote and all nested double quotes need to be escaped (\" instead of "). JSON validators will mark this string as malformed JSON but it is still parsable with JSON.parse
In the second case you print string "interpreted" as JSON by console.log. JSON validators will mark it as valid JSON but it is no parsable with JSON.parse because it is not string (no quotes around)

getting json from string

I have the following json object
"phrase": "{subject: Hello}"
When I access "phrase" it returns "{subject: Hello}" as a string but I want this string to be converted to json object.
There is a function called JSON.parse to convert things from strings to objects but I am not sure it would apply to your case, since you have invalid JSON (the "Hello" not being quoted is a bid deal and the "subject" not being quoted is a bad sign)
If it's a Javascript object literal, just remove the quotation marks when you create it:
var phrase = { subject: "Hello" };
If it's a JSON string that is parsed, change the string to an object:
{ "phrase": { "subject": "Hello" } }
If you have a variable that contains a JSON string, you need to make it valid JSON to parse it:
var phrase = '{ "subject": "Hello" }';
var obj = JSON.parse(phrase);
You can also parse the string as Javascript, which has a more relaxed syntax. The string value needs delimiters though:
var phrase = '{ subject: "Hello" }';
var obj = eval(phrase);
Note that the eval function actually executes the string as javascript, so you need to know where the string value comes from for this to be safe.
Use JSON.parse():
var obj = {myObj:"{\"this\":\"that\"}"};
obj.myObj = JSON.parse(obj.myObj);
alert(obj.myObj["this"]);
Here is the demo.
you could use native JSON parsing with JSON.parse(jsonString);
(Edit: assuming to have a valid JSON object)

Categories