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?
JSON strings do not allow real newlines in its data; it can only have escaped newlines. Snowflake allows escaping the newline character by the use of an additional backslash character.
JSON.stringify() calls toJSON with one parameter, the key , which has the same semantic as the key parameter of the replacer function: if this object is a property value, the property name. if it is in an array, the index in the array, as a string.
JavaScript Object Notation (JSON) is a standard text-based format for representing structured data based on JavaScript object syntax. It is commonly used for transmitting data in web applications (e.g., sending some data from the server to the client, so it can be displayed on a web page, or vice versa).
Data from an untrusted source is not sanitized by the server and written directly to a JSON stream. This is referred to as server-side JSON injection. Data from an untrusted source is not sanitized and parsed directly using the JavaScript eval function. This is referred to as client-side JSON injection.
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.
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);
Try the following code:
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);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With