Reputation: 95
I'm new to javascript and i want to count the values of this json string:
{
"files": [
{
"name": "doc1.pdf",
"title": "networking",
"path": "mfpreader.comze.com\/files\/doc1.pdf"
},
{
"name": "doc2.pdf",
"title": "Armoogum",
"path": "mfpreader.comze.com\/files\/doc2.pdf"
}
]
}
the json is saved in the res.responseJSON.data.
here is the code i tried:
$("#demo").html(JSON.stringify(res.responseJSON.data));
var jsonObject = JSON.parse(res.responseJSON.data);
var propertyNames = Object.keys(jsonObject);
alert("There are "+propertyNames.length+" properties in the object");
The value is get is 1. It should be 2 since we have 2 documents.
can i have some please. Thanks
Upvotes: 3
Views: 3408
Reputation: 59
Assign
json
response to a variable i.e.
var result = {"files":[{"name":"doc1.pdf","title":"networking","path":"mfpreader.comze.com/files/doc1.pdf"},{"name":"doc2.pdf","title":"Armoogum","path":"mfpreader.comze.com/files/doc2.pdf"}]}
Now Count Files
result.files.length
output : 2
Upvotes: 1
Reputation: 9510
Simply use res.responseJSON.data.files.length
$("#demo").html(JSON.stringify(res.responseJSON.data));
//var jsonObject = JSON.parse(res.responseJSON.data);
//var propertyNames = Object.keys(jsonObject);
alert("There are "+res.responseJSON.data.files.length+" properties in the object");
Upvotes: 0
Reputation: 197
DhruvPathak is correct - your solution is returning 1 since there is only 1 key at the root layer of the JSON object.
If you want to count the number of keys in the lower layers, you could do something like:
$("#demo").html(JSON.stringify(res.responseJSON.data));
var jsonObject = JSON.parse(res.responseJSON.data);
var numProperties = 0;
for (item in jsonObject) {
numProperties += Object.keys(item).length;
}
alert("There are " + numProperties + " properties in the object");
You can find the number of properties in any layer of the JSON object by using nested for
loops.
Hope this helps!
Upvotes: 0
Reputation: 1687
For the required output what you want you have to do like below
var v={"files":[{"name":"doc1.pdf","title":"networking","path":"mfpreader.comze.com\/files\/doc1.pdf"},{"name":"doc2.pdf","title":"Armoogum","path":"mfpreader.comze.com\/files\/doc2.pdf"}]};
console.log(v.files.length)
Upvotes: 5
Reputation: 43235
Your json object has only 1 key at root level. i.e. "files"
jsonObject = {"files":[{"name":"doc1.pdf","title":"networking","path":"mfpreader.comze.com\/files\/doc1.pdf"},{"name":"doc2.pdf","title":"Armoogum","path":"mfpreader.comze.com\/files\/doc2.pdf"}]}
Object.keys(jsonObject)
// will return -> ["files"]
Upvotes: 0