如何在javascript

时间:2018-10-30 18:54:15

标签: javascript json

我有这个json:

  

[{“ date”:“ 2018-04-09”,“ count”:8},{“ date”:“ 2018-04-10”,“ count”:3},{“ date”:“ 2018-04-12“,” count“:4},{” date“:” 2018-04-13“,” count“:11},{” date“:” 2018-04-14“,” count“ :1},{“ date”:“ 2018-04-15”,“ count”:4},{“ date”:“ 2018-04-16”,“ count”:8},{“ date”:“ 2018-04-17“,” count“:34}]

如何使用JSON.parse()解析?

我尝试使用JSON.parse(response); 也可以这样:

               for(var x = 0; x < response.length; x++){
                 var stat = JSON.parse(response[x]);
               }

,但不能同时使用。

响应对象是上面是数组的JSON!

这是两种情况下的错误:

  

VM96:1未捕获的SyntaxError:JSON中位置1处的意外令牌o       在JSON.parse()       在Object.ajaxsuccess上[成功](登录:40)       在你(jquery.min.js:2)       在Object.fireWith [as resolveWith](jquery.min.js:2)       在k(jquery.min.js:2)       在XMLHttpRequest。 (jquery.min.js:2)

3 个答案:

答案 0 :(得分:0)

假设您上面的参数是一个字符串-

response = "[{"date":"2018-04-09","count":8},{"date":"2018-04-10","count":3},{"date":"2018-04-12","count":4},{"date":"2018-04-13","count":11},{"date":"2018-04-14","count":1},{"date":"2018-04-15","count":4},{"date":"2018-04-16","count":8},{"date":"2018-04-17","count":34}]"

先解析然后浏览每个条目-

for(var x = 0; x < response.length; x++){
  var stat = response[x];
  //stat = {"date":"2018-04-09","count":8}
}

但是请确保假设使用response。您可能是指response.body或某些派生词。

答案 1 :(得分:0)

假设响应是您发布的json

您可以

response = JSON.parse(response)
for (let x of response) {
    console.log(x.date) // If you want the date property
    console.log(x.count) // If you want the count property
}

作为旁注,如果您这样做

var stat = x

就像您的示例一样,它将覆盖stat变量,并且您只会获得上一次迭代的值。因此,您应该使用数组

小提琴:https://jsfiddle.net/epo4f5rb/1/

答案 2 :(得分:0)

JSON.parse()需要一个字符串作为输入并返回一个Javascript对象。

https://www.w3schools.com/js/js_json_parse.asp