How do I get the key value in a JSON object and the length of the object using JavaScript?
For example:
[
{
"amount": " 12185",
"job": "GAPA",
"month": "JANUARY",
"year": "2010"
},
{
"amount": "147421",
"job": "GAPA",
"month": "MAY",
"year": "2010"
},
{
"amount": "2347",
"job": "GAPA",
"month": "AUGUST",
"year": "2010"
}
]
Here, length of this array is 3. For getting, value is fine ([0].amount)
, in index[0]
it has three name value pairs.
So, I need to get the name (like amount or job... totally four name) and also how do I count how many names there are?
This question is related to
javascript
json
You may need:
Object.keys(JSON[0]);
To get something like:
[ 'amount', 'job', 'month', 'year' ]
Note: Your JSON is invalid.
When you parse the JSON representation, it'll become a JavaScript array of objects.
Because of this, you can use the .length
property of the JavaScript array to see how many elements are contained, and use a for
loop to enumerate it.
Try out this
var str ="{ "name" : "user"}";
var jsonData = JSON.parse(str);
console.log(jsonData.name)
//Array Object
str ="[{ "name" : "user"},{ "name" : "user2"}]";
jsonData = JSON.parse(str);
console.log(jsonData[0].name)
JSON content is basically represented as an associative array in JavaScript. You just need to loop over them to either read the key or the value:
var JSON_Obj = { "one":1, "two":2, "three":3, "four":4, "five":5 };
// Read key
for (var key in JSON_Obj) {
console.log(key);
console.log(JSON_Obj[key]);
}
You can simply traverse through the object and return if a match is found.
Here is the code:
returnKeyforValue : function() {
var JsonObj= { "one":1, "two":2, "three":3, "four":4, "five":5 };
for (key in JsonObj) {
if(JsonObj[key] === "Keyvalue") {
return key;
}
}
}
Source: Stackoverflow.com