0

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.

8
  • 1
    JSON.parse converts a JSON string to a javascript object 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 Commented Dec 7, 2016 at 1:03
  • 1
    That's not a valid JSON. Keys have to be surrounded with quotes. 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. Commented Dec 7, 2016 at 1:07
  • 1
    Why did you remove the quotes in the JSON text? Commented Dec 7, 2016 at 1:10

8 Answers 8

2

You 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);

Sign up to request clarification or add additional context in comments.

8 Comments

@user3270763 my pleasure
Wait, so you are removing the quotes from the JSON reply (as you mentioned in your other comment) and then adding them back in? It sounds like the server was giving you perfectly valid JSON which you could have just left alone.
You can do that by simply putting a + in front of each of the values when you use it. For example, assume that you have one of your array elements (with lat and lng properties in a variable called location. Then you can use new google.maps.LatLng( +location.lat, +location.lng ) to create a proper LatLng object with numeric values.
You should definitely not be using regular expressions for any of this. The best thing is to fix the server code to generate proper JSON with numeric values for lat and lng. But failing that, you can use + as mentioned above to convert the numeric strings to actual numbers.
I posted an answer that explains the + operator along with some other things.
|
2

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.

3 Comments

Will throw an exception because that string is not a valid JSON
I used JSON.parse and it's giving me this error when I try to plot it : ValueError: not an Array
This is true. It's not valid JSON. The lat and lng need to be wrapped in double quotes.
2

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.com/maps/api/js"></script>
<div id="map_canvas"></div>

1 Comment

Thank you for that elaborate code. It will be helpful if my code to add polylines dynamically doesnt work out!
1

The simplest way is eval.

var str = "[{lat:42.021631,lng:-93.624239},{lat:19.112049,lng:72.870234}]";
eval(str);

Comments

1

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.

Comments

1

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.

Comments

1

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]

Comments

-1

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"}]')

1 Comment

I get ValueError: at index 0: not a LatLng or LatLngLiteral: in property lat: not a number

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.