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(/;/, "") + "}")
});
-
What is source of these strings? fixing source would be first choicecharlietfl– charlietfl2015年08月22日 17:53:13 +00:00Commented Aug 22, 2015 at 17:53
-
@charlietfl, its from an MVC view. How should i change the source fields?user3281114– user32811142015年08月22日 17:54:26 +00:00Commented Aug 22, 2015 at 17:54
-
2presumably that data is being turned into string from some initial organized structure. Creating proper json at that point would simplify itcharlietfl– charlietfl2015年08月22日 17:56:25 +00:00Commented Aug 22, 2015 at 17:56
2 Answers 2
The strings in JSON must be in doublequotes.
Replace (/address/, '"address"') in your code with (/address: (.+)/, '"address": "1ドル"')
answered Aug 22, 2015 at 17:53
woxxom
75.2k15 gold badges161 silver badges164 bronze badges
Sign up to request clarification or add additional context in comments.
Comments
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.
answered Aug 22, 2015 at 18:17
dda
6,2212 gold badges27 silver badges37 bronze badges
Comments
lang-js