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"}'
Related
In my application when I enter value as my"name in text field the framework makes a String like (this i can not control):
"[{\"id\":\"201500000001002\",\"name\":\"my\"name\",\"colorCode\":\"\",\"version\":\"11\",\"nodeOrder\":\"1\"}]"
Now this String is passed to JSON.parse() method which produces an error because of ambiguous name field as
\"name\":\"my\"name\"
var str = JSON.parse("[{\"id\":\"201500000001002\",\"name\":\"my\"name\",\"colorCode\":\"\",\"version\":\"11\",\"nodeOrder\":\"1\"}]")
This results in JSON exception
Is there anything I can do with the string:
"[{\"id\":\"201500000001002\",\"name\":\"my\"name\",\"colorCode\":\"\",\"version\":\"11\",\"nodeOrder\":\"1\"}]"
To escape double quote character in my " name as my \" name to make it valid for JSON.parse method.
I can not control JSON String, I am just passing name as my"name and framework creates a String which is passed to JSON.parse()
I went through a series of text replace. You can try this:
var str = "[{\"id\":\"201500000001002\",\"name\":\"my\"name\",\"colorCode\":\"\",\"version\":\"11\",\"nodeOrder\":\"1\"}]";
JSON.parse(
str.replace(/\\/i,"").
replace(/{"/g,"{'").
replace(/":"/g,"':'").
replace(/","/g,"','").
replace(/"}/g,"'}").
replace(/'/g,"\###").
replace(/"/g,"\\\"").
replace(/###/g,"\"")
);
It will give back your desired JSON array
var str = "[{\"id\":\"201500000001002\"}]";
str.replace("\"*","\\\"");
var obj = JSON.parse(str);
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.
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
}
I am using the following JS code to parse a JSON string from a separate JS file:
// extract JSON from a module's JS
var jsonMatch = data.match( /\/\*JSON\[\*\/([\s\S]*?)\/\*\]JSON\*\// );
data = JSON.parse( jsonMatch ? jsonMatch[1] : data );
This is an example of the JS file I extract the JSON string from:
JsonString = /*JSON[*/{"entities":[{"type":"EntityPlayer","x":88,"y":138}]}/*]JSON*/;
This code works just fine, however if the JS file with the JSON string contains carriage returns and isn't on one complete line then I get a syntax error.
Example:
JsonString = /*JSON[*/{
"entities":[{
"type":"EntityPlayer",
"x":88,
"y":138}]
}/*]JSON*/;
Returns the following error:
JSON.parse: unexpected non-whitespace character after JSON data
Any idea how I could modify my parsing to work by either stripping out whitespace or to remove carriage returns and new line spaces?
data = JSON.parse( (jsonMatch ? jsonMatch[1] : data).replace(/\n/g,"") );
Did not test it, but maybe this is what you are looking for?
var JsonString = JsonString.replace(new RegExp( "\\n", "g" ),"");
(from http://www.bennadel.com/blog/161-Ask-Ben-Javascript-Replace-And-Multiple-Lines-Line-Breaks.htm)
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)