【问题标题】:Count the values in json using javascript使用javascript计算json中的值
【发布时间】:2016-07-13 22:20:24
【问题描述】:

我是 javascript 新手,我想计算这个 json 字符串的值:

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

json 保存在 res.responseJSON.data 中。

这是我尝试过的代码:

$("#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");

get 的值为 1。它应该是 2,因为我们有 2 个文档。

请给我一些。谢谢

【问题讨论】:

标签: javascript json


【解决方案1】:

json 响应分配给变量,即

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

现在统计文件数

result.files.length

输出:2

【讨论】:

    【解决方案2】:

    只需使用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");
    

    【讨论】:

      【解决方案3】:

      DhruvPathak 是正确的 - 您的解决方案返回 1,因为 JSON 对象的根层只有 1 个键。

      如果您想计算较低层中的键数,您可以执行以下操作:

       $("#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");
      

      您可以使用嵌套的for 循环查找 JSON 对象的任何层中的属性数量。

      希望这会有所帮助!

      【讨论】:

        【解决方案4】:

        对于所需的输出,您需要执行如下操作

        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)
        

        【讨论】:

        • 谢谢大家
        【解决方案5】:

        您的 json 对象在根级别只有 1 个键。即“文件”

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

        【讨论】:

          猜你喜欢
          • 2023-02-06
          • 2020-09-04
          • 2020-11-20
          • 1970-01-01
          • 2016-06-29
          • 2011-08-13
          • 2020-07-14
          • 2015-07-30
          • 2020-06-12
          相关资源
          最近更新 更多