简体   繁体   English

JSON.parse() 不工作

[英]JSON.parse() not working

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 响应函数中,我通过方法参数jsonObject捕获了前面提到的相同 json -

//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?谁能告诉我为什么我收到错误?

Your JsonObject seems is a Json Object.您的 JsonObject 似乎是一个 Json 对象。 The reasons why you can't parse Json from a String:无法从 String 解析 Json 的原因:

  • the String is surround by " " .字符串由" "包围。 and use \" escape inside. Here is an 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 " .当您尝试通过JSON.parse()解析上面的字符串时,仍然返回一个字符串: {"name":"alan","age":34} ,并且\"被替换为" But use the JSON.parse() function again, it will return the object you want.但是再次使用JSON.parse()函数,它会返回你想要的对象。 So in this case,you can do this:所以在这种情况下,你可以这样做:

    JSON.parse(JSON.parse("{\"name\":\"alan\",\"age\":34}" ))

  • Your string use ' instead of " . example:您的字符串使用'而不是" 。例如:

    {'name':'alan','age':34}

    if you try to parse above string by JSON.parse() , may cause error如果您尝试通过JSON.parse()解析上述字符串,可能会导致错误

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.如果服务器正在发送有效的 JSON,我认为您不应该调用JSON.parse(jsonObject) ,因为它会在检索响应时自动解析。 I believe that if You set the Content-type: application/json header it will be parsed automatically.我相信如果您设置Content-type: application/json标头,它将被自动解析。

Try using jsonObject as if it was already parsed, something like:尝试使用jsonObject ,就好像它已经被解析过一样,例如:

console.log(jsonObject.canApprove);

Without calling JSON.parse before.之前没有调用JSON.parse

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 需要一个字符串。

Your jsonObject seems 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));
    }
}
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.您可以在创建字符串时使用"而不是'

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) {

    }
});

I faced similar problem and now it's solved.我遇到了类似的问题,现在已经解决了。 I'm using ASP.Net MVC to send value to .js file.我正在使用 ASP.Net MVC 将值发送到 .js 文件。 The problem was that I was returning JsonResult from the Action method, because of this JSON.parse was failing in .js file.问题是我从 Action 方法返回 JsonResult,因为这个 JSON.parse 在 .js 文件中失败。 I changed the return type of Action method to string, now JSON.parse is working fine.我将 Action 方法的返回类型更改为字符串,现在 JSON.parse 工作正常。

This answer might help someone who's storing JSON as a string in SQL databse.这个答案可能会对将 JSON 作为字符串存储在 SQL 数据库中的人有所帮助。

I was storing the value of following我正在存储关注的价值

JSON.stringify({hi:hello})

in MySQL.在 MySQL 中。 The JSON stored in SQL was {"hi":"hello"}存储在 SQL 中的 JSON 是{"hi":"hello"}

Problem was when I read this value from db and fed it to JSON.parse() it gave me error.问题是当我从 db 读取这个值并将其提供给JSON.parse()时,它给了我错误。

I tried wrapping it in quotes but didn't work.我尝试用引号括起来,但没有用。

Finally following worked最后以下工作

JSON.parse(JSON.stringify(jsonFromDb))

This worked and JSON was parsed correctly.这行得通,并且正确解析了 JSON。

I know the storing mechanisim might not be appropriate however those were client needs.我知道存储机制可能不合适,但这是客户的需求。

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.我从中学到的是,可能是 PHP 编码 json 对象的方式对 JavaScript 来说并不熟悉。

var receivedData = data.toString()
receivedData = JSON.parse(receivedData)
console.log(receivedData.canApprove)

This will work.这将起作用。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM