var myvar = '
myname({ "country":{ "cities":[ {"id":"3", "population":"3700"},{"id":"5", "population":"3730"}] } });';
So that myvar
is a string.
How to get citiesArr
array of city
objects from myvar
?
var myvar = '
myname({ "country":{ "cities":[ {"id":"3", "population":"3700"},{"id":"5", "population":"3730"}] } });';
So that myvar
is a string.
How to get citiesArr
array of city
objects from myvar
?
Make it valid JSON first by removing myname(
at beginning and );
at the end, use String#replace
for that. After that parse the string using JSON.parse
method and get the data you want.
var myvar = 'myname({ "country":{ "cities":[ {"id":"3", "population":"3700"},{"id":"5", "population":"3730"}] } });';
console.log(JSON.parse(myvar.replace(/^\s*\w+\(|\);$/g, '')).country.cities);
this is not a json object, it contains a function, JSON is only a javascript object.
to get this you might need to use eval, although i dont recommend.
var myvar = 'myname({ "country":{ "cities":[ {"id":"3", "population":"3700"},{"id":"5", "population":"3730"}] } });';
function myname(jsonObj) {
console.log(jsonObj)
}
eval(myvar); //will log the whole object.
Change your json to
var myvar = { "country":{ "cities":[ {"id":"3", "population":"3700"},{"id":"5", "population":"3730"}] } };
and you can get the cities as myvar.country["cities"]
JSON is valid JavaScript, but not all valid JavaScript is valid JSON.
As Nina pointed out in comments on the question, the string you've pasted in your question might be valid JavaScript, but it is not valid JSON.
Once you've corrected that problem, you can use this solution to parse your JSON:
var myvar = '{"country":{"cities":[{"id":"3", "population":"3700"},{"id":"5", "population":"3730"}]}}';
var theData = JSON.parse(myvar);
How to get citiesArr array of city objects from myvar?
Once you've used JSON.parse(...)
to get back an object, you can use it like you'd normally use an object:
var myvar = '{"country":{"cities":[{"id":"3", "population":"3700"},{"id":"5", "population":"3730"}]}}';
var theData = JSON.parse(myvar);
var cities = theData.country.cities;
console.log(cities);
If you're not getting the string from a third party (like a file or a web server) then you may want to consider just building the object the normal way rather than trying to use strings of JSON at all:
var myvar = {"country":{"cities":[{"id":"3", "population":"3700"},{"id":"5", "population":"3730"}]}};