Javascript JSON.parse() 不起作用
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/30194562/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
JSON.parse() not working
提问by Razib
I have a json from my server which is -
我的服务器上有一个 json,它是 -
{"canApprove": true,"hasDisplayed": false}
I can parse the json like this -
我可以像这样解析 json -
var msg = JSON.parse('{"canApprove": true,"hasDisplayed": false}');
alert(msg.canApprove); //shows true.
At my ajax response function I caught the same json mentioned earlier by a method parameter jsonObject-
在我的 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
}
But now I got the following error -
但现在我收到以下错误 -
SyntaxError: JSON.parse: unexpected character at line 1 column 2 of the JSON data
SyntaxError: JSON.parse: JSON 数据第 1 行第 2 列的意外字符
Can anyone tell me why I am getting the error?
谁能告诉我为什么我收到错误?
采纳答案by taxicala
I dont think you should call JSON.parse(jsonObject)if the server is sending valid JSON as it will be parsed automatically when it retrieves the response. I believe that if You set the Content-type: application/jsonheader it will be parsed automatically.
JSON.parse(jsonObject)如果服务器发送有效的 JSON,我认为您不应该调用,因为它会在检索响应时自动解析。我相信,如果您设置Content-type: application/json标题,它将被自动解析。
Try using jsonObjectas if it was already parsed, something like:
尝试使用jsonObject,就好像它已经被解析一样,例如:
console.log(jsonObject.canApprove);
Without calling JSON.parsebefore.
JSON.parse之前没有打电话。
回答by alan9uo
Your JsonObject seems is a Json Object. The reasons why you can't parse Json from a String:
你的 JsonObject 似乎是一个 Json 对象。无法从 String 解析 Json 的原因:
the String is surround by " ". and use \"escape inside example:
"{\"name\":\"alan\",\"age\":34}"when you try to parse above string by JSON.parse(), still return the a string:{"name":"alan","age":34}, and \"is replace by ". But use the JSON.parse() again, it will return the object you want. So in this case,you can do this:
JSON.parse(JSON.parse("{\"name\":\"alan\",\"age\":34}" ))use 'instead of ". example:
{'name':'alan','age':34}when you try to parse above string by JSON.parse(), may cause error
字符串被" "包围。并在示例中使用\"转义:
"{\"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() 解析上述字符串时,可能会导致错误
回答by baao
Its already an object, no need to parse it. Simply try
它已经是一个对象,不需要解析它。简单地尝试
alert(jsonObject.canApprove)
in your response function.
在您的响应函数中。
Json.parse is expecting a string.
Json.parse 需要一个字符串。
回答by R3tep
Your jsonObjectseems already parsed, you need to test if this is the case.
您的jsonObject似乎已经解析,您需要测试是否是这种情况。
function(jsonObject){
var msg = (typeof jsonObject == "object" ? jsonObject : JSON.parse(jsonObject));
}
It's also possible that your call back is empty, it's generates the same error if you try to parse an empty string. So test the call back value.
您的回调也可能为空,如果您尝试解析空字符串,则会生成相同的错误。所以测试回调值。
function(jsonObject){
if(jsonObject) {
var msg = (typeof jsonObject == "object" ? jsonObject : JSON.parse(jsonObject));
}
}
回答by Emmanouil Chountasis
Here is an example of how to make an ajax call and parse the result:
以下是如何进行 ajax 调用并解析结果的示例:
var query = {
sUserIds: JSON.stringify(userIds),
};
$.ajax({
type: "POST",
url: your-url,
data: JSON.stringify(query),
contentType: "application/json; charset=utf-8",
dataType: "json",
async: true,
success: function (response) {
var your_object = JSON.parse(response.d);
},
failure: function (msg) {
alert(msg);
},
error: function (a, b, c) {
}
});
回答by Yagiz
var text = '{"canApprove": true,"hasDisplayed": false}';
var parsedJSON = JSON.parse(text);
alert(parsedJSON.canApprove);
This works. It is possible that you use "instead of 'while creating a String.
这有效。您可以在创建字符串时使用"而不是'。
回答by Raj
I faced similar problem and now it's solved. I'm using ASP.Net MVC to send value to .js file. The problem was that I was returning JsonResult from the Action method, because of this JSON.parse was failing in .js file. I changed the return type of Action method to string, now JSON.parse is working fine.
我遇到了类似的问题,现在已经解决了。我正在使用 ASP.Net MVC 将值发送到 .js 文件。问题是我从 Action 方法返回 JsonResult,因为这个 JSON.parse 在 .js 文件中失败。我将 Action 方法的返回类型更改为字符串,现在 JSON.parse 工作正常。
回答by Danny Sofftie
As someone mentioned up there, this actually fixes the problem. What I learnt from this is that may be how PHP encodes a json object is not familiar to JavaScript.
正如有人在那里提到的,这实际上解决了问题。我从中学到的是,JavaScript 不熟悉 PHP 编码 json 对象的方式。
var receivedData = data.toString()
receivedData = JSON.parse(receivedData)
console.log(receivedData.canApprove)
This will work.
这将起作用。

