使用 JavaScript 将字符串转换为 JSON



我有一个看起来像这样的string

"{""c1"": ""value1"", ""c2"": ""value2""}"

如您所见,它是 JSON 格式。我将其存储在SQLITE数据库中,然后使用以下Javascript代码以JSON格式再次获取它:

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 "]));

但是我收到此错误:

<JSContext: 0x1c0044aa0> SyntaxError: JSON Parse error: Expected '}' 

你能告诉我为什么我有这个错误吗,我花了几个小时试图解决它但没有成功。如有必要,我可以更改string格式,我所需要的只是从SQLITE再次获取它作为JSON对象。 提前谢谢你。

你的那个字符串不是有效的 JSON,这个是,基于你的字符串内容。

'{"c1": "value1", "c2": "value2"}'

如您所见,键/值对被一个双引号"包围,而不是两个,整个带有单引号的字符串'。如果整个字符串使用双引号,则需要对内部字符串进行转义,如下所示

"{"c1": "value1", "c2": "value2"}"

有关 JSON 的进一步阅读,这篇文章有很多

  • 正确的 JSON 内容类型是什么?

下面是显示其输出的示例

// 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""}") );

您的字符串格式不正确。这就是为什么 JSON.parse(( 无法读取它的原因。

您的字符串:

"{""c1"": ""value1"", ""c2"": ""value2""}"

试着把它做成这样:

'{"c1": "value1", "c2": "value2"}'

最新更新