3

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

Sverri M. Olsen
  • 13,055
  • 3
  • 36
  • 52
Gunesh.John
  • 95
  • 2
  • 8

5 Answers5

5

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)
shreyansh
  • 1,637
  • 4
  • 26
  • 46
1

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

Shashank
  • 2,010
  • 2
  • 18
  • 38
0

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"]
DhruvPathak
  • 42,059
  • 16
  • 116
  • 175
0

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!

Jeremy D
  • 197
  • 2
  • 13
0

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");
Moumit
  • 8,314
  • 9
  • 55
  • 59