如何解析和检索行分隔的JSON?

时间:2018-02-23 19:44:27

标签: javascript json

我从我的网络服务器使用请求req.open("GET", ".../cgi-bin/data_file.json", true);获取json文件,JSON文件看起来像这样(由换行符分隔):

{"priority": "Low", "taskName": "Fry eggs", "userID": "Max", "description": "buy the eggs first "} 

{"priority": "Medium", "taskName": "buy car", "userID": "Jonathan", "description": " "}

{"priority": "Medium", "taskName": "Make dough", "userID": "Danielle", "description": " dough fresh"}`

当我解析它时 - var jsonData = JSON.parse(req.responseText);如何获取任何密钥的每个单独值?

1 个答案:

答案 0 :(得分:-1)

使用for-in循环。



var lines = `
{"priority": "Low", "taskName": "Fry eggs", "userID": "Max", "description": "buy the eggs first "} 

{"priority": "Medium", "taskName": "buy car", "userID": "Jonathan", "description": " "}

{"priority": "Medium", "taskName": "Make dough", "userID": "Danielle", "description": " dough fresh"}`.split("\n").forEach(resp => {
  if (!resp.trim()) return;
  var obj = JSON.parse(resp);
  for (var key in obj) {
    if (obj.hasOwnProperty(key))
      console.log(key + " is " + obj[key]);
  }
});




或者您可以使用Object.keys()



var lines = `
{"priority": "Low", "taskName": "Fry eggs", "userID": "Max", "description": "buy the eggs first "} 

{"priority": "Medium", "taskName": "buy car", "userID": "Jonathan", "description": " "}

{"priority": "Medium", "taskName": "Make dough", "userID": "Danielle", "description": " dough fresh"}`.split("\n").forEach(resp => {
  if (!resp.trim()) return;
  var obj = JSON.parse(resp);
  var keys = Object.keys(obj);
  for (var i = 0; i < keys.length; i++) {
    console.log(keys[i] + " is " + obj[keys[i]]);
  }
});
&#13;
&#13;
&#13;