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

4

5 Answers 5

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)
Sign up to request clarification or add additional context in comments.

1 Comment

Thank you all guys
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

Comments

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"]

Comments

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!

Comments

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");

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.