Reputation: 2639
I have a JSON file in my project that looks like this:
{"_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}}
I'm not sure how to loop through each line to put it in an array. How can I do this?
Upvotes: 8
Views: 7978
Reputation: 81
What about using map properly?
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);
Upvotes: 7
Reputation: 207511
Split on new lines, join with comma, wrap it with brackets, and parse it.
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);
Better solution, fix whatever gives you that format to give you the correct structure to start out with.
Upvotes: 10