JSON Array exception using json string field - javascript

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.

Related

Javascript JSON.stringify change my string that contains backslash

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.

Cast a string to JSON using JavaScript

I have a string that looks like this:
"{""c1"": ""value1"", ""c2"": ""value2""}"
As you can notice, it is in JSON format. I store it in an SQLITE database, and then I use the following Javascript code to get it again in JSON format :
var req= "SELECT json_column from my_table";
var result = execSQL(req);
for (var index in res) {
var row= res[index];
consoleLog("test getad ", JSON.parse(row["json_column "]));
But I get this error :
<JSContext: 0x1c0044aa0> SyntaxError: JSON Parse error: Expected '}'
Can you please tell me why I have this error, I've spent hours trying to resolve it but with no success. I can change the string format if it is necessary, all I need is to get it again from SQLITE as JSON object.
Thank you in advance.
That string of yours is not valid JSON, this one is, based on your string content.
'{"c1": "value1", "c2": "value2"}'
As you can see the key/value pair is surrounded with one double quote ", not two, and the whole string with single quotes '. If the whole string would use double quote, the inner one's would needed to be escaped, like this
"{\"c1\": \"value1\", \"c2\": \"value2\"}"
For further reading about JSON, this post has a lot
What is the correct JSON content type?
Here is a sample showing their output
// these gets properly printed
// correct formatted JSON
console.log( JSON.parse('{"c1": "value1", "c2": "value2"}') );
// correct formatted JSON, outer doulbe quotes and inner, escaped one's
console.log( JSON.parse("{\"c1\": \"value1\", \"c2\": \"value2\"}") );
// yours wrapped with single quotes and inner double quotes, changed to one
console.log( JSON.parse('{""c1"": ""value1"", ""c2"": ""value2""}'.replace(/""/g, '"')) );
// these generates script error
// yours wrapped with single quotes
console.log( JSON.parse('{""c1"": ""value1"", ""c2"": ""value2""}') );
// yours as is, and had to comment this out, as if not, it crashes itself and all the above
//console.log( JSON.parse("{""c1"": ""value1"", ""c2"": ""value2""}") );
Your string is not in the right format. That is why the JSON.parse() cannot read it.
Your string:
"{""c1"": ""value1"", ""c2"": ""value2""}"
Try making it like this:
'{"c1": "value1", "c2": "value2"}'

JSON.parse() failing to deserialize the last index of an array containing JSON strings

I have a string that looks like this:
{"name":"Bob","age":20}###{"name":"Brian","age":12}###{"name":"Ryan","age":19}
As you can see, they JSON-like strings are demarcated by ###
My JS Code looks like this:
var data = <above string passed in from a function>
var data_list = data.split('###'); //should return an array with 3 JSON strings
Now I am trying to parse them individually like this:
console.log(JSON.parse(data_list[0])) // returns [object Object]
console.log(JSON.parse(data_list[1])) // returns [object Object]
BUT, the last one:
console.log(JSON.parse(data_list[2])) // Fails
Error:
Invalid JSON: <json>:28:1 Expected eof but found
}
^ in <eval> at line number 28
ALSO:
I printed out the contents of each index from the data_list array and they are valid JSON as per jsonlint.com
As per Bergi's comments I was able to replace the \u0000\u0000\u0000\u0000 using replace(/\0/g, '') and the JSON is now valid. Thanks Bergi!
You could try this code, to transform that string into an array of JSON objects.
var array = [];
var uniqueString = '[' + data.replaceAll('###', ', ') + ']';
array = JSON.parse(uniqueString);
Now 'array' is an array of JSON parsed object, so you should be able to obtain something like this.
array[0] will be '{"name": "Bob", "age": 20}'
please check your data string, it may have some invisible character as #Bergi said.
I already check by pasting your string as below.
var sample = '{"name":"Bob","age":20}###{"name":"Brian","age":12}###{"name":"Ryan","age":19}';
var data_str = sample.split('###');
console.log(JSON.parse(data_str[0]));
console.log(JSON.parse(data_str[1]));
console.log(JSON.parse(data_str[2]));
Output Was on console::
Object {name: "Bob", age: 20}
VM981:4 Object {name: "Brian", age: 12}
VM981:5 Object {name: "Ryan", age: 19}
While the bane of a programmer's existence are quotes, i.e. single vs double and when to use which, the issue here concerns the integrity of the data. One may note that the numbers in the string are unquoted, but that is okay -- still valid JSON; see this discussion. The actual problem stems from the data being tainted with trailing unseen null characters. One may cleanse the data with a simple regex as in the attached example.
var data = '{"name":"Bob","age":20}###{"name":"Brian","age":12}###{"name":"Ryan","age":19}\u0000\u0000\u0000\u0000';
var clean_data = data.replace(/\u0000/g,"");
var data_list = clean_data.split('###');
console.log(JSON.parse(data_list[0]))
console.log(JSON.parse(data_list[1]))
console.log(JSON.parse(data_list[2]))
See this discussion
One needs to exercise caution before accepting data as valid regardless as to the source. If a string happens to acquire one or more characters detrimental to JSON, such as null or vertical tab characters, the data becomes compromised. One should assume the data is tainted until proven otherwise. A regex that replaces any occurrences of such characters helps ensure the validity of the data. Whether those characters are represented in unicode or as escape codes is immaterial. The important point is to replace any such occurrences with empty strings; see here.

convert invalid JSON string to JSON

I have an invalid json string like following,
"{one: 'one', two: 'two'}"
I tried to use JSON.parse to convert it to an object. however, this is not valid json string.
Is there any functions can convert this invalid format into a valid json string or directly convert into an object?
IF your example syntax is the same as your real JSON, JSONLint says you need double quote for the name AND the value.
In this case only, use these replace calls:
var jsontemp = yourjson.replace((/([\w]+)(:)/g), "\"$1\"$2");
var correctjson = jsontemp.replace((/'/g), "\"");
//yourjson = "{one: 'one', two: 'two'}"
//jsontemp = "{"one": 'one', "two": 'two'}"
//correctjson = "{"one": "one", "two": "two"}"
However you should try to work with a valid Json in the first place.
If the question is "can I convert invalid JSON into valid JSON", in the general case the answer is obviously "no"; where would you even start with a string like "$#!~~"?
In this particular case, the JSON is only invalid because the property names are not quoted; as JavaScript, the string is valid and could be parsed using, for example,
var myObj = eval( "x=" + myString );
or better
var myObj = (new Function("return " + myString))();
However, this is potentially very unsafe and you should not do it unless you are positive the string cannot cause harm (which seems unlikely if you aren't in a position to generate valid JSON in the first place). It also won't help you if the JSON code is invalid in other ways, and it will fail if the property names are not valid JS identifiers.
For a proper answer it would be useful to know more about the context of this question.

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
}

Categories