【问题标题】:How to read the JSON Array with Javascript to get the value if it exists如何使用 Javascript 读取 JSON 数组以获取值(如果存在)
【发布时间】:2015-09-25 13:51:57
【问题描述】:

这是我的 JSON 代码。我将这个 json 存储在一个数组中。

{
"kind": "urlshortener#url",
"id": "http://goo.gl/2FIrtF",
"longUrl": "http://hike.com/?utm_source=facebook",
"status": "OK",
"created": "2015-09-22T13:45:53.645+00:00",
"analytics": {
    "allTime": {
        "shortUrlClicks": "1",
        "longUrlClicks": "1",
        "referrers": [
            {
                "count": "1",
                "id": "unknown"
            }
        ],
        "countries": [
            {
                "count": "1",
                "id": "IN"
            }
        ],
        "browsers": [
            {
                "count": "1",
                "id": "Chrome"
            }
        ],
        "platforms": [
            {
                "count": "1",
                "id": "Macintosh"
            }
        ]
    },
    "month": {
        "shortUrlClicks": "1",
        "longUrlClicks": "1",
        "referrers": [
            {
                "count": "1",
                "id": "unknown"
            }
        ],
        "countries": [
            {
                "count": "1",
                "id": "IN"
            }
        ],
        "browsers": [
            {
                "count": "1",
                "id": "Chrome"
            }
        ],
        "platforms": [
            {
                "count": "1",
                "id": "Macintosh"
            }
        ]
    },
    "week": {
        "shortUrlClicks": "1",
        "longUrlClicks": "1",
        "referrers": [
            {
                "count": "1",
                "id": "unknown"
            }
        ],
        "countries": [
            {
                "count": "1",
                "id": "IN"
            }
        ],
        "browsers": [
            {
                "count": "1",
                "id": "Chrome"
            }
        ],
        "platforms": [
            {
                "count": "1",
                "id": "Macintosh"
            }
        ]
    },
    "day": {
        "shortUrlClicks": "0",
        "longUrlClicks": "0"
    },
    "twoHours": {
        "shortUrlClicks": "0",
        "longUrlClicks": "0"
    }
},
"result": {
    "kind": "urlshortener#url",
    "id": "http://goo.gl/2FIuvF",
    "longUrl": "http://hike.com/?utm_source=facebook",
    "status": "OK",
    "created": "2015-09-22T13:45:53.645+00:00",
    "analytics": {
        "allTime": {
            "shortUrlClicks": "1",
            "longUrlClicks": "1",
            "referrers": [
                {
                    "count": "1",
                    "id": "unknown"
                }
            ],
            "countries": [
                {
                    "count": "1",
                    "id": "IN"
                }
            ],
            "browsers": [
                {
                    "count": "1",
                    "id": "Chrome"
                }
            ],
            "platforms": [
                {
                    "count": "1",
                    "id": "Macintosh"
                }
            ]
        },
        "month": {
            "shortUrlClicks": "1",
            "longUrlClicks": "1",
            "referrers": [
                {
                    "count": "1",
                    "id": "unknown"
                }
            ],
            "countries": [
                {
                    "count": "1",
                    "id": "IN"
                }
            ],
            "browsers": [
                {
                    "count": "1",
                    "id": "Chrome"
                }
            ],
            "platforms": [
                {
                    "count": "1",
                    "id": "Macintosh"
                }
            ]
        },
        "week": {
            "shortUrlClicks": "1",
            "longUrlClicks": "1",
            "referrers": [
                {
                    "count": "1",
                    "id": "unknown"
                }
            ],
            "countries": [
                {
                    "count": "1",
                    "id": "IN"
                }
            ],
            "browsers": [
                {
                    "count": "1",
                    "id": "Chrome"
                }
            ],
            "platforms": [
                {
                    "count": "1",
                    "id": "Macintosh"
                }
            ]
        },
        "day": {
            "shortUrlClicks": "0",
            "longUrlClicks": "0"
        },
        "twoHours": {
            "shortUrlClicks": "0",
            "longUrlClicks": "0"
        }
    }
}

}

在上面的 JSON 中,我们怎样才能得到分析 -> 天 -> 国家的存在?

我想先知道国家是否存在,如果不存在,显示一些价值。如果存在,它将尝试获取特定国家/地区的计数。

我从过去 5 个小时开始尝试这个,没有任何运气。

if(arr.analytics.day.countries !== undefined) {
         function thingscount(arr, platf) {
           var x = arr.analytics.day.countries.map(function(el) {
           return (platf.indexOf(el.id) != -1) ? parseInt(el.count) : 0; });
           var count = 0;
           for (var i = 0; i < x.length; i++) count += x[i];
           return count; 
           }       

        var one = thingscount(arr, ["US"]); 

        }else{
           var one = 0;

        }

如果当天有国家/地区,上面的代码可以正常工作,但有时,在我的 JSON 中将没有平台部分,在这种情况下它给了我

Uncaught TypeError: Cannot read property 'map' of undefined

我需要一种方法来检查平台是否存在,是否需要计数,是否没有为变量提供其他值。

更新:

我正在使用下面的代码来获取 IN 的计数。

当它有 IN 键和值时,它会给我结果。但是当它没有 IN 键时,它会显示“未定义计数”错误。

var month_inclicks = arr.analytics.month.countries.filter(function(el) { return el.id == "IN"; })[0].count;

如果我们要查找的键不存在,我们如何设置默认值?

【问题讨论】:

  • 那不是 JSON。 jsonlint.com
  • 抱歉,更新了有效的 JSON。

标签: javascript java php arrays json


【解决方案1】:

虽然这不是 JSON,但我假设它是一个 javascript 对象。话虽如此,您需要考虑使用 hasOwnProperty 方法或 in 关键字。

例子:

if (arr.total.limited.hasOwnProperty('platforms')) { //do stuff

if ('platforms' in arr.total.limited) { //do something

【讨论】:

  • 刚刚更正了 json。你能再检查一下这个问题吗?
  • 仍然无效,见jsonlint.com。也就是说,它并没有真正改变我的答案。如果您已经将其编组为 javascript 对象,则可以简单地使用 hasOwnPropertyin
  • 我正在使用下面的代码来获取 IN 的计数。当它具有 IN 键和值时,它会给我结果。但是当它没有 IN 键时,它会显示“未定义计数”错误。 var month_inclicks = arr.analytics.month.countries.filter(function(el) { return el.id == "IN"; })[0].count;如果我们要找的key不存在怎么设置默认值?
  • 请在您的问题中发布此类更新,而不是作为评论链。显然这种格式有点难读。
【解决方案2】:

我已更正您的 JSON。按照@CollinD 的建议使用hasOwnProperty

var arr = {
    total: {
        limited: {
            things: "451",
            platforms: [{
                count: "358",
                id: "Windows"
            }, {
                count: "44",
                id: "X11"
            }, {
                count: "42",
                id: "Macintosh"
            }, {
                count: "2",
                id: "Linux"
            }, {
                count: "1",
                id: "iPhone"
            }, {
                count: "1",
                id: "iPod"
            }]

        }
    }
};

Object.prototype.hasOwnProperty()

console.log(arr.total.limited.hasOwnProperty('platforms'));

DEMO

【讨论】:

    【解决方案3】:

    作为记录,您可以使用 reduce 将地图和“thingscount”函数中的计数滚动到一个操作中:

    var getCount = function getCount( ary, find ) {
        return ary.reduce(function ( acc, record) {
            if (find.indexOf(record.id) !== -1) acc += parseInt(record.count, 10);
            return acc;
        }, 0);
    };
    

    内联用法:

    if (arr.analytics.day.hasOwnProperty('countries')) {
        var find = ['IN'],
            count = arr.analytics.day.countries.reduce(function ( acc, record) {
                if (find.indexOf(record.id) !== -1) acc += parseInt(record.count, 10);
                return acc;
            }, 0);
    }
    

    或者用函数:

    if (arr.analytics.day.hasOwnProperty('countries')) {
        var count = getCount(arr.analytics.day.countries, ['US','IN']);
    }
    

    【讨论】:

    • 如果使用空数组作为输入,将找不到 indexOf 并返回默认的 acc(umulator) 值 0。像getCount(arr.analytics.day.countries, []); 应该返回 0。
    • if (find.indexOf(record.id) !== -1) 更改为if (find.indexOf(record.id) !== -1 &amp;&amp; record.hasOwnProperty('count')) 如果您的国家/地区有 id 但没有计数,则不会引发错误。 0 来自 reduce 本身,因为我们传入 0 作为 'acc' 的起始值。所有在 'find' 数组中且有 count 值的国家,将被添加到我们传入的 0 中。如果 find 数组为空,或者数组中没有国家有 count,则我们传入的 0 in 永远不会添加一个数字,因此结果保持为 0。
    • 当我尝试使用函数时,它给了我Uncaught TypeError: Cannot read property 'reduce' of undefined 错误。我放置了第一个函数并按照第三个示例中所示使用。当我使用第二个代码时,它给了我未定义的输出。
    • 那么您可能尝试在不存在的阵列上使用它。如果您将使用第二个代码,请检查它是否具有“国家”属性来更新它。或者只是使用你原来的计数方式。祝你好运。
    • 第二个代码工作正常。但是我需要在页面中多次使用它,所以要寻找一个可以工作的函数:) 这个函数可能有什么问题?
    猜你喜欢
    • 1970-01-01
    • 2019-06-26
    • 2023-03-27
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-07-05
    • 1970-01-01
    相关资源
    最近更新 更多