如何在JavaScript中逐行遍历换行符分隔的json?

时间:2017-03-09 23:56:48

标签: javascript arrays json

我的项目中有一个JSON文件,如下所示:

{"_id":707860,"name":"Hurzuf","country":"UA","coord":{"lon":34.283333,"lat":44.549999}}
{"_id":519188,"name":"Novinki","country":"RU","coord":{"lon":37.666668,"lat":55.683334}}
{"_id":1283378,"name":"Gorkhā","country":"NP","coord":{"lon":84.633331,"lat":28}}

我不确定如何遍历每一行以将其放入数组中。我怎么能这样做?

3 个答案:

答案 0 :(得分:6)

拆分新行,用逗号连接,用括号括起来,然后解析它。



var str = `{"_id":707860,"name":"Hurzuf","country":"UA","coord":{"lon":34.283333,"lat":44.549999}}
{"_id":519188,"name":"Novinki","country":"RU","coord":{"lon":37.666668,"lat":55.683334}}
{"_id":1283378,"name":"Gorkhā","country":"NP","coord":{"lon":84.633331,"lat":28}}`

var lines = str.split(/\n/);
var wrapped = "[" + lines.join(",") + "]";
var obj = JSON.parse(wrapped);

console.log(obj);




更好的解决方案,修复任何给你这种格式的东西,以便为你提供正确的结构。

答案 1 :(得分:1)

请尝试以下代码:



var myVar = `{"_id":707860,"name":"Hurzuf","country":"UA","coord":{"lon":34.283333,"lat":44.549999}}
{"_id":519188,"name":"Novinki","country":"RU","coord":{"lon":37.666668,"lat":55.683334}}
{"_id":1283378,"name":"Gorkhā","country":"NP","coord":{"lon":84.633331,"lat":28}}`;

var myArray = [];
myVar.split('\n').map(function (value) {
  myArray.push(JSON.parse(value));
});
console.log(myArray);




答案 2 :(得分:1)

如何正确使用地图?

var myVar = `{"_id":707860,"name":"Hurzuf","country":"UA","coord":{"lon":34.283333,"lat":44.549999}}
{"_id":519188,"name":"Novinki","country":"RU","coord":{"lon":37.666668,"lat":55.683334}}
{"_id":1283378,"name":"Gorkhā","country":"NP","coord":{"lon":84.633331,"lat":28}}`;

var myArray = myVar.split('\n').map(JSON.parse);
console.log(myArray);