在javascript中解析python json响应

时间:2015-11-15 04:11:24

标签: javascript jquery json

我在jquery中解析json响应。

console.log(response)给出了

{"result": [{"surprise": "24.79%"}, {"joy": "18.73%"}, {"anticipation": "14.61%"}, {"disgust": "10.54%"}, {"sadness": "8.75%"}, {"trust": "8.32%"}, {"anger": "8.12%"}, {"fear": "6.14%"}]}

我试图将这个json解析为变量,如下所示:

val res = JSON.parse(response);
document.getElementById("anger").innerHTML = res['result'][6]['anger'];
document.getElementById("disgust").innerHTML = res['result'][3]['disgust'];
document.getElementById("fear").innerHTML = res['result'][7]['fear'];
document.getElementById("joy").innerHTML = res['result'][1]['joy'];
document.getElementById("sadness").innerHTML = res['result'][4]['sadness'];
document.getElementById("surprise").innerHTML = res['result'][0]['surprise'];
document.getElementById("trust").innerHTML = res['result'][5]['trust'];
document.getElementById("anticipation").innerHTML = res['result'][2]['anticipation'];

给出了

Uncaught SyntaxError: Unexpected identifier

val res = JSON.parse(response);

我在这里做错了什么?

2 个答案:

答案 0 :(得分:0)

val更改为var

var response = '{"result": [{"surprise": "24.79%"}, {"joy": "18.73%"}, {"anticipation": "14.61%"}, {"disgust": "10.54%"}, {"sadness": "8.75%"}, {"trust": "8.32%"}, {"anger": "8.12%"}, {"fear": "6.14%"}]}';


var res = JSON.parse(response);
document.getElementById("anger").innerHTML = res['result'][6]['anger'];
document.getElementById("disgust").innerHTML = res['result'][3]['disgust'];
document.getElementById("fear").innerHTML = res['result'][7]['fear'];
document.getElementById("joy").innerHTML = res['result'][1]['joy'];
document.getElementById("sadness").innerHTML = res['result'][4]['sadness'];
document.getElementById("surprise").innerHTML = res['result'][0]['surprise'];
document.getElementById("trust").innerHTML = res['result'][5]['trust'];
document.getElementById("anticipation").innerHTML = res['result'][2]['anticipation'];
<div id="anger"></div>
<div id="disgust"></div>
<div id="fear"></div>
<div id="joy"></div>
<div id="sadness"></div>
<div id="surprise"></div>
<div id="trust"></div>
<div id="anticipation"></div>

答案 1 :(得分:0)

首先,您需要将“val”更改为“var”。然后我就是这样做的:

res.result.forEach( function(elem){
    for (var e in elem){
        $('.' + e).html(elem[e]);
    }
});

这是一个小提琴: https://jsfiddle.net/mckinleymedia/pc2q917f/