0

Here's the string.

{lat: -37.819616, lng: 144.968119},
{lat: -38.330766, lng: 144.695692},
{lat: -39.927193, lng: 175.053218},
{lat: -41.330162, lng: 174.865694},
{lat: -42.734358, lng: 147.439506},
{lat: -42.734358, lng: 147.501315},
{lat: -42.735258, lng: 147.438000},
{lat: -43.999792, lng: 170.463352}

I'm trying to convert to hash object like this.

[    
{lat: -37.819616, lng: 144.968119},
{lat: -38.330766, lng: 144.695692}
]

How should I do in Javascript?

[Resolved] I confused regarding with how to express hash in Javascript and in JSON file. In Javascript

var locations = [ {lat: 35.123, lng: 127.111}, {lat: 35.222, lng: 111.222} ];

In JSON

[
{ "lat": 35.123, "lng": 127.111 },
{ "lat": 35.222, "lng": 111.222}
]

I got mixed up 2 way of writings. Thanks anyway.

Noriaki Takamizawa
  • 887
  • 1
  • 10
  • 25

3 Answers3

3

Your string is not proper, JSON parser will never parse it properly. Here you can't use eval() function approach. It's not like an Array but a HashMap or simply malformed Object. In your case, You need json with key-value pair combination.

{'lat': -37.819616, 'lng': 144.968119},
{'lat': -38.330766, 'lng': 144.695692}

If Your Object does not contains child objects/arrays you can use the following code.

function formatJSON2Array (str) {
    var arr = [];
    str = str.replace(/^\{|\}$/g,'').split(',');
    for(var i=0,cur,pair;cur=str[i];i++){
        arr[i] = {};
        pair = cur.split(':');
        arr[i][pair[0]] = /^\d*$/.test(pair[1]) ? +pair[1] : pair[1];
    }
  console.log("JSON Array>>> " +JSON.stringify(arr)); // it will print [{"a":12},{"b":"c"},{"foo":"bar"}] in console
    return arr;
}

formatJSON2Array("{lat: -37.819616, lng: 144.968119},{lat: -38.330766, lng: 144.695692}");

Above code will convert your entered string into Array of objects.

If however you actually wanted a HashMap (Associative Array) and NOT an array, use the following code:

function FormatJSON2Object(str) {
    var obj = {};
    str = str.replace(/^\{|\}$/g,'').split(',');
    for(var i=0,cur,pair;cur=str[i];i++){
        pair = cur.split(':');
        obj[pair[0]] = /^\d*$/.test(pair[1]) ? +pair[1] : pair[1];
    }
  console.log("JSON Object >>> "+ JSON.stringify(obj)); // it will return {"lat":" -37.819616"," lng":" 144.695692","{lat":" -38.330766"}
    return obj;
}

FormatJSON2Object("{lat: -37.819616, lng: 144.968119},{lat: -38.330766, lng: 144.695692}");

Please note that, above code will become a lot more complex when you start nesting objects and arrays with it. This thread helped me a lot for this JSON conversions with array-objects and parsing. If you have any key value pair except lat lng, it will work fine.

Rakshit Shah
  • 438
  • 4
  • 13
  • 1
    I checked google maps api document. According this, {lat: -123, lng: 123}is not wrong. See here https://developers.google.com/maps/documentation/javascript/examples/map-latlng-literal?hl=en – Noriaki Takamizawa Feb 25 '18 at 11:50
  • 1
    @NoriakiTakamizawa, Yes I agree with that document, You can use JSON parse directly. If you want to customize your response, if you added some key-value pair for map Options like data, zoom, content or anything else, In that case above code snippets will work perfectly. – Rakshit Shah Feb 25 '18 at 13:56
  • Thanks for the reply. Finally, I find out what the difference between your code and google's. I'm going to append what I noticed. – Noriaki Takamizawa Feb 26 '18 at 02:12
0

This simple line should do it (and work with nested values if need be):

JSON.parse('[' + string.replace(/(\w+)\s*:/g, '"$1":') + ']')

Test it here:

let string = `
  {lat: -37.819616, lng: 144.968119},
  {lat: -38.330766, lng: 144.695692},
  {lat: -39.927193, lng: 175.053218},
  {lat: -41.330162, lng: 174.865694},
  {lat: -42.734358, lng: 147.439506},
  {lat: -42.734358, lng: 147.501315},
  {lat: -42.735258, lng: 147.438000},
  {lat: -43.999792, lng: 170.463352}`;

let result = JSON.parse('[' + string.replace(/(\w+)\s*:/g, '"$1":') + ']');

console.log(result);
Jeto
  • 14,596
  • 2
  • 32
  • 46
-2
JSON.parse("{\"a\":\"b\"}")

{ a: 'b' }

陈敏华
  • 1,365
  • 1
  • 9
  • 9