admin管理员组文章数量:1396811
I have this JSON String:
"[{"lat":"42.021631","lng":"-93.624239"},{"lat":"19.112049","lng":"72.870234"}]"
I need it in this format to be able to plot using Google Maps which uses this:
var flightPlanCoordinates = [
{lat: 37.772, lng: -122.214},
{lat: 21.291, lng: -157.821},
{lat: -18.142, lng: 178.431},
{lat: -27.467, lng: 153.027}
];
How do I get this in the format? I've received my string after using Papa Parse to import CSV and removed the quotes in the JSON text. Any help will be appreciated.
I have this JSON String:
"[{"lat":"42.021631","lng":"-93.624239"},{"lat":"19.112049","lng":"72.870234"}]"
I need it in this format to be able to plot using Google Maps which uses this:
var flightPlanCoordinates = [
{lat: 37.772, lng: -122.214},
{lat: 21.291, lng: -157.821},
{lat: -18.142, lng: 178.431},
{lat: -27.467, lng: 153.027}
];
How do I get this in the format? I've received my string after using Papa Parse to import CSV and removed the quotes in the JSON text. Any help will be appreciated.
Share Improve this question edited Dec 7, 2016 at 1:17 user3270763 asked Dec 7, 2016 at 0:56 user3270763user3270763 1251 gold badge3 silver badges13 bronze badges 8-
1
JSON.parse
converts a JSON string to a javascript object – geocodezip Commented Dec 7, 2016 at 0:59 - I get an error with that if I pass the result to Google Maps: ValueError: not an Array – user3270763 Commented Dec 7, 2016 at 1:03
- 1 That's not a valid JSON. Keys have to be surrounded with quotes. – Mati Commented Dec 7, 2016 at 1:03
- I guess the problem is in you server-side. You need to stringify the json array before sending it. – Jerry Chen Commented Dec 7, 2016 at 1:07
- 1 Why did you remove the quotes in the JSON text? – castletheperson Commented Dec 7, 2016 at 1:10
8 Answers
Reset to default 2You string is not an json format, so you first translate it to json format.
let str = "[{lat:42.021631,lng:-93.624239},{lat:19.112049,lng:72.870234}]";
let jsonStr = str.replace(/(lat|lng)/g, '"' + "$1" + '"');
let json = JSON.parse(jsonStr);
console.log(json);
JSON.parse(<json string variable>)
will return a JS object that you can pass into google maps.
However: your JSON is not valid: "[{lat:42.021631,lng:-93.624239},{lat:19.112049,lng:72.870234}]"
. The lat and lngs should be wrapped with double quotes.
JSON.parse converts a JSON string to a javascript object. If you leave the quotes in so it is valid JSON:
'[{"lat":42.021631,"lng":-93.624239},{"lat":19.112049,"lng":72.870234}]'
This will create a polyline:
var path = JSON.parse('[{"lat":42.021631,"lng":-93.624239},{"lat":19.112049,"lng":72.870234}]');
console.log(path);
var polyline = new google.maps.Polyline({
map: map,
path: path
});
code snippet:
function initialize() {
var map = new google.maps.Map(
document.getElementById("map_canvas"), {
center: new google.maps.LatLng(0, 0),
zoom: 1,
mapTypeId: google.maps.MapTypeId.ROADMAP
});
var path = JSON.parse('[{"lat":42.021631,"lng":-93.624239},{"lat":19.112049,"lng":72.870234}]');
var polyline = new google.maps.Polyline({
map: map,
path: path
});
}
google.maps.event.addDomListener(window, "load", initialize);
html,
body,
#map_canvas {
height: 100%;
width: 100%;
margin: 0px;
padding: 0px
}
<script src="https://maps.googleapis./maps/api/js"></script>
<div id="map_canvas"></div>
The simplest way is eval.
var str = "[{lat:42.021631,lng:-93.624239},{lat:19.112049,lng:72.870234}]";
eval(str);
You should try to keep the quotes ...
x = "[{lat:42.021631,lng:-93.624239},{lat:19.112049,lng:0},{lat:42.112049,lng:0}]".split("},{");
var regex = /[+-]?\d+(\.\d+)?/g;
flightPlanCoordinates = [];
for (var i=0; i<x.length; i++) {
coords = x[i].match(regex).map(function(v) { return parseFloat(v); });
if (coords.length === 2) {
flightPlanCoordinates.push({ "lat": coords[0], "lng": coords[1] });
}
}
console.log(flightPlanCoordinates);
Kris Roofe's answer is quite nice.
The real problem here, given the latest update to your question, is that the lat
and lng
values in your JSON data are strings instead of numbers.
In other words, where your JSON data looks like this (whitespace added for clarity):
[
{ "lat": "42.021631", "lng": "-93.624239" },
{ "lat": "19.112049", "lng": "72.870234" }
]
it should look like this:
[
{ "lat": 42.021631, "lng": -93.624239 },
{ "lat": 19.112049, "lng": 72.870234 }
]
The best way to fix this is to change your server code to generate that second format instead of the first one. I can't give specifics because I don't know what server language or libraries you are using. But if you can get the server to generate the lat
and lng
values as the numbers they should be instead of strings, everything will get easier.
If that can't be done, the solution is not to be mucking around with the JSON text, stripping out quotes or adding them back in with regular expressions. That is just creating a mess that you don't need and doesn't help you.
Instead, simply convert the lat
and lng
values to numbers where you need to.
For example, if you have the first element of your JSON array in a variable called location
, you may be trying to create a LatLng
object from it like this:
var latlng = new google.maps.LatLng( location.lat, location.lng );
That may not work, because location.lat
and location.lng
are strings, not numbers. But you can easily convert them to numbers:
var latlng = new google.maps.LatLng( +location.lat, +location.lng );
There are several ways to convert a string to a number, but the unary +
operator is the most succinct.
How does the +
operator work? It isn't specific to Google Maps or the LatLng
object or anything like that. It's simply a JavaScript operator. If you apply the +
operator to something that is already a number, it just leaves it alone. But if you apply +
to a string, it converts it to a number.
Alternatively, you could use the parseFloat
function:
var latlng = new google.maps.LatLng(
parseFloat(location.lat),
parseFloat(location.lng)
);
There's nothing wrong with that if you find it more clear, but try the +
operator: once you get used to it, you may find you like it.
Again, though, the best solution is to fix the server code to generate proper JSON numbers as illustrated above.
That isn't a valid JSON. If the string is from a trusted source, you could use eval.
var result = eval([{lat:42.021631,lng:-93.624239},{lat:19.112049,lng:72.870234}])
Will return
[Object, Object]
You need to keep the quotes in the JSON text and run this line:
var flightPlanCoordinates = JSON.parse('[{"lat":"42.021631","lng":"-93.624239"},{"lat":"19.112049","lng":"72.870234"}]')
本文标签: javascriptSplit JSON into multiple variables an arrayStack Overflow
版权声明:本文标题:javascript - Split JSON into multiple variables an array - Stack Overflow 内容由网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:http://www.betaflare.com/web/1744144690a2592779.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
发表评论