Reputation: 1981
I am trying to get a value from json by using the JSON.parse
function. My json response is given below:
{
"rows": 10,
"os": "0",
"page": "1",
"total": "122",
"projects": {
"P143841": {
"id": "P143841",
"locations": [{
"geoLocId": "0002220957",
"latitude": "3.866667",
"longitude": "11.516667"
}],
}
}
}
I am able to get the value 10 if I do JSON.parse(obj.rows)
but if I assign the rows to a variable say var value = rows
and then I pass it to the JSON.parse(obj.value)
function I got undefined
.
P.S. I won't be knowing the names of the response parameters, i.e. i won't know if it will be rows
or os
quoting from the above example. I will be retrieving them from a database. If I perform the code below:
for (var i=0;i<length;i++) {
var value = responseParam_array[i];
console.log(obj.value);
}
I get the output but any help will be much appreciated.
Upvotes: 4
Views: 16214
Reputation: 150070
As per the other answers you shouldn't need to parse individual properties, just parse the original JSON and then operate on the resulting object.
But as for this problem:
"if I assign the rows to a variable say
var value = rows
and then I pass it to theJSON.parse(obj.value)
function I gotundefined
"
If value
is a variable holding the name of a property of obj
then you need:
obj[value]
// NOT
obj.value
When you use "dot" notation the part on the right of the dot is taken as the literal name of the property, not as a variable. Using the square-bracket syntax the expression in the brackets is evaluated and its result is taken as the property name.
Upvotes: 6
Reputation: 13809
If I understand your question:
var str = '{ "some": "JSON String like the one above with", "rows": 10 }';
var parsed = JSON.parse(str);
var whatYouWant = parsed.rows;
Upvotes: 0
Reputation: 14434
you should be json-parsing your whole object and using the parsed object afterwards (you dont need to parse every property for itself)
var strObj = '{"rows": 10,"os": "0","page": "1","total": "122","projects":{"P143841":{"id":"P143841",}}';
var obj = JSON.parse(strObj);
var rows = obj.rows;
Upvotes: 1