Raz*_*zib 6 javascript ajax json
我有一个来自服务器的json,它是-
{"canApprove": true,"hasDisplayed": false}
Run Code Online (Sandbox Code Playgroud)
我可以这样解析json-
var msg = JSON.parse('{"canApprove": true,"hasDisplayed": false}');
alert(msg.canApprove); //shows true.
Run Code Online (Sandbox Code Playgroud)
在我的Ajax响应函数我赶上了相同的JSON早些时候方法的参数中提到jsonObject-
//response function
function(jsonObject){
//here jsonObject contains the same json - {"canApprove":true,"hasDisplayed": false}
//But without the surrounding single quote
//I have confirmed about this by seeing my server side log.
var msg = JSON.parse(jsonObject); // this gives the error
}
Run Code Online (Sandbox Code Playgroud)
但是现在我遇到了以下错误-
SyntaxError:JSON.parse:JSON数据的第1行第2列出现意外字符
谁能告诉我为什么我得到这个错误?
tax*_*ala 14
JSON.parse(jsonObject)如果服务器发送有效的 JSON,我认为您不应该调用,因为它会在检索响应时自动解析。我相信,如果您设置Content-type: application/json标题,它将被自动解析。
尝试使用jsonObject,就好像它已经被解析一样,例如:
console.log(jsonObject.canApprove);
Run Code Online (Sandbox Code Playgroud)
JSON.parse之前没有打电话。
ala*_*9uo 12
你的 JsonObject 似乎是一个 Json 对象。无法从 String 解析 Json 的原因:
字符串被" "包围。并在示例中使用\"转义:
"{\"name\":\"alan\",\"age\":34}"
当您尝试通过 JSON.parse() 解析上述字符串时,仍然返回字符串:{"name":"alan","age":34},并且 \"被替换为"。但是再次使用 JSON.parse() ,它将返回您想要的对象。所以在这种情况下,你可以这样做:
JSON.parse(JSON.parse("{\"name\":\"alan\",\"age\":34}" ))
使用'而不是 "。例如:
{'name':'alan','age':34}
当您尝试通过 JSON.parse() 解析上述字符串时,可能会导致错误
这个答案可能会对那些将 JSON 作为字符串存储在 SQL 数据库中的人有所帮助。
我正在存储以下值
JSON.stringify({hi:hello})
Run Code Online (Sandbox Code Playgroud)
在 MySQL 中。SQL 中存储的 JSON 是{"hi":"hello"}
问题是当我从数据库读取这个值并将其提供给JSON.parse()它时出现错误。
我尝试将其用引号括起来,但没有成功。
最后以下工作成功了
JSON.parse(JSON.stringify(jsonFromDb))
Run Code Online (Sandbox Code Playgroud)
这有效并且 JSON 被正确解析。
我知道存储机制可能不合适,但这是客户的需求。