0

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(/;/, "") + "}")
});
3
  • What is source of these strings? fixing source would be first choice Commented Aug 22, 2015 at 17:53
  • @charlietfl, its from an MVC view. How should i change the source fields? Commented Aug 22, 2015 at 17:54
  • 2
    presumably that data is being turned into string from some initial organized structure. Creating proper json at that point would simplify it Commented Aug 22, 2015 at 17:56

2 Answers 2

2

The strings in JSON must be in doublequotes.

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

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

Comments

0
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.

Comments

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.