1

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.

ABK
  • 511
  • 1
  • 7
  • 19

2 Answers2

1

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

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""}") );
Asons
  • 84,923
  • 12
  • 110
  • 165
-1

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"}'
  • 1
    Now your last 3 answers, started from this, is the same solution as an existing answer, posted long time before yours. Why do you do that? ... That is not appropriate and you should not do that. – Asons Jul 11 '18 at 14:06