Jason Neering Jason Neering - 4 months ago 17
C# Question

javascript convert a pre-formatted array string to a usable array in js

I have what I hope is a simple question, though it may be that I am going about it the wrong way from the start, so let me explain.

I am drawing polygons on a google map as the user drags/zooms the map. So on dragend/zoom change I fire off a javascript method that calls a webAPI that returns a "string" that is pre-formatted to javascript array format (in the past we used this using <%= getdata() %> with no problems.

The string is usually quite long, but a sample with only 3 points is here:

"{lat: 36.206133, lng: -95.81533},{lat: 36.222298, lng: -95.814961},{lat: 36.22445, lng: -95.81527}"

Now, I see exactly what is happening. I just do not know how to fix it. Its treating it as a string, so when I try:

var array = [ data ]; (where data is the string returned above), it fails as it is not an array of coordinate objects as expected, but a single member array of a string.

So... a question with 2 parts: 1, is there a better way to do this, and if not, how do I cast that "string" as an array of coordinate objects just as if that was typed directly in to javascript?



As @jmesolomon already commented, you could/should use JSON.parse for this.

However, this would require the input string to be of a valid JSON format. Currently that's not the case because of two things:

1) The object's keys aren't of the type 'string'. Change: Wrap the keys with double quotation marks.

2) The response actually is a comma seperated list of objects, but not defined as an array because there's no matching '[' + ']' tags. Change: Make sure the WebAPI to format the response as an actual javascript array by adding '[' + ']' tags.


var originalInput = "{lat: 36.206133, lng: -95.81533},{lat: 36.222298, lng: -95.814961},{lat: 36.22445, lng: -95.81527}";

var workingInput ='{"lat": 36.206133, "lng": -95.81533},{"lat": 36.222298, "lng": -95.814961},{"lat": 36.22445, "lng": -95.81527}';

var betterInput ='[{"lat": 36.206133, "lng": -95.81533},{"lat": 36.222298, "lng": -95.814961},{"lat": 36.22445, "lng": -95.81527}]';

console.log("workingInput", JSON.parse("[" + workingInput + "]"));
console.log("betterInput", JSON.parse(betterInput));