简体   繁体   中英

JSON parsing array into objects

I have an array of components like this:

var names =
    1)"lat: 40.6447077, lng: -73.878421, address: 1600 Pennsylvania Avenue, Brooklyn, NY 11239, USA"
    2)"lat: 40.609099, lng: -73.931516, address: 2015 E. 35th street, Brooklyn, Ny, United States"

I am trying to parse this into an array of objects. The following code works great for parsing the latitude and longitude, yet am receiving unexpected token errors when attempting to parse the address too.

    var newArray = names.map(function (str) {
    return JSON.parse("{" + str.replace(/lat/, '"lat"').replace(/lng/, '"lng"').replace(/address/, '"address"').replace(/;/, "") + "}")
});

The strings in JSON must be in doublequotes.

Replace (/address/, '"address"') in your code with (/address: (.+)/, '"address": "$1"')

names.map(function (str) {
  return JSON.parse(
    "{" + str.replace(/address: /, 'address: "').replace(/(\w+): /g, '"$1": ')+'"}'
  );
});

You have first to wrap the address date within quotes, as it is not only text but has commas in it. Confusion galore. Then you wrap words before : within quotes too.

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM