Im trying to convert a chunk of coordinates(lat/lng) into a json object with no luck at all. I want each line to be a pair.
I have a string that looks like this (+ 200 ish lines)
67.8574074243696,20.2120303794714
67.8570072289646,20.2137432009361
67.8562768208083,20.2153228755138
67.8558962489713,20.216419476191
I want to convert it into a json object that looks like this:
[
{
"lat": xx.xxxxx,
"lng": xx.xxxxxxx
},
{
"lat": xx.xxxxx,
"lng": xx.xxxxxxx
}
]
you can read line by line and pass to this function:
function parseCoordinates(coordinates){
var tmpCoord = coordinates.split(',');
return ({ 'lat': tmpCoord[0], 'lng': tmpCoord[1] });
}
var coords = array();
coords.push(parseCoordinates(lines1);
coords.push(parseCoordinates(lines2);
Or if the real chunk is for example in a variable wich name is chunk you can simply do something like that:
First separate chunk into lines:
var lines = chunk.match(/[^\r\n]+/g);
then loop and call previous function.
var coords = array();
for(var i = 0; i< lines.length; i++){
coords.push(parseCoordinates(lines[i]);
}
In my answer I assume your string is a csv.
You want to do something like:
var result = [];
var rows = csv.split('\n');
for(i in rows)
{
var row = rows[i],
values = row.split(',');
result.push({
lat: values[0],
lng: values[1]
});
}
json_result = JSON.stringify(result);
var obj = JSON.parse(string);
其中 string 是您的 json 字符串。
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.