如何获取json格式字符串(从表中提取)的值

时间:2016-06-03 02:20:16

标签: javascript jquery json

我从这样的表中提取了一个json格式数据:

[ { id:"3",
"Date Extracted":"12/3",
Experiment:"normal"},
{ id:"2",
"Date Extracted":"12/3",
Experiment:"powder",
Notes:"" },
{ id:"1",
"Date Extracted":"12/3",
Experiment:"fine",
Notes:"" }
]

我使用下面的功能只获取每个ID的属性,例如" 12/3","普通",不包括名称,如" Date Extracted& #34;,实验。 不知怎的,这不起作用。 但我不知道具体细节如何。

var j = JSON.parse(data);

function(){
for(name in j.property.name)
console.log(j.property.value);
}

3 个答案:

答案 0 :(得分:0)

提取的json数据与属性名称有一些验证问题。您可以通过jsonlint.com验证您的jsondata。

所以json数据应该是:

var jsonData ='[{ "id":"3", "Date Extracted":"12/3","Experiment":"normal"}, { "id":"2","Date Extracted":"12/3","Experiment":"powder","Notes":"" },{ "id":"1","Date Extracted":"12/3","Experiment":"fine","Notes":"" }]';

功能:

var json = $.parseJSON(jsonData);
$(json).each(function(i,val){
    $.each(val,function(name,value){
        console.log(name + " : " + value);       
    });
});

答案 1 :(得分:0)

你不能像那样使用“for”。

var j = JSON.parse('[{  "id": "3",  "Date Extracted": "12/3",   "Experiment": "normal"}, {  "id": "2",  "Date Extracted": "12/3",   "Experiment": "powder", "Notes": ""}, { "id": "1",  "Date Extracted": "12/3",   "Experiment": "fine",   "Notes": ""}]');for(var i=0;i<j.length;i++){
var obj = j[i];
for(var key in obj){
    var attrName = key;
    var attrValue = obj[key];
    console.log(attrValue);
}}

答案 2 :(得分:0)

&#13;
&#13;
var data = [{
  id: "3",
  "Date Extracted": "12/3",
  Experiment: "normal"
}, {
  id: "2",
  "Date Extracted": "12/3",
  Experiment: "powder",
  Notes: ""
}, {
  id: "1",
  "Date Extracted": "12/3",
  Experiment: "fine",
  Notes: ""
}];





for (var i = 0; i < data.length; i++) {
  console.log("Date Extracted " + data[i]['Date Extracted'])//for index Date Extracted
  console.log("Experiment " + data[i]['Experiment'])//for index Experiment
}
&#13;
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
&#13;
&#13;
&#13;

你可以像这样使用for循环