如何从JSON对象中的数组获取键名及其值

如何从JSON对象中的数组获取键名及其值

本文介绍了如何从JSON对象中的数组获取键名及其值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的问题

在我的JSON文件中,我在一个对象中有一个对象,该对象的值是键/值对的数组.我在输出每个键名及其值时遇到麻烦.

In my JSON file I have an object within an object with a value which is an array of key/value pairs. I am having trouble outputting each key name and its value.

我的代码

menu.json

{"themenu":[
    {
        "stuff": "stuffs",
        "pages": [
            {"name1": "page111"},
            {"name2": "page222"},
            {"name3": "page333"}
        ]
    }
]}

menu.js

$(function() {
    $.getJSON('menu.json', function(data) {
        $(data.themenu).each(function() {
            var stuff = this.stuff;
            alert(stuff); // alerts 'stuffs'
            $(this.pages).each(function(key, value) {
                var pageName = this.key;
                var pageUrl = this.value;
                alert(pageName + ' ' + pageUrl);
            })
        })
    })
})

我需要什么

我想输出键的名称及其对应的值,以便与此相同...

I want to output the name of the key and its corresponding value so it would be the same as this...

alert('name1 page111');
alert('name2 page222');
alert('name3 page333');

我尝试过的事情

我尝试了一些事情,包括...

I've tried a few things including...

$(data.pages).each(function(key, value) {
    var pageName = this.key;
    var pageUrl = this.value;
})

...还有更多我不为所动的伏都教.

...and a bunch more voodoo that I'm too embarrassed to post.

推荐答案

只需使用此代码,它将起作用.我只是更改了代码的某些内容,请尝试以下操作::

Just use this code, it will work. I just changed some content of your code, try this::

var json_data = {"themenu":[
    {
        "stuff": "stuffs",
        "pages": [
            {"name1": "page111"},
            {"name2": "page222"},
            {"name3": "page333"}
        ]
    }
]};
$(document).ready(function() {
//  $.getJSON(json_data, function(data) {
        $(json_data.themenu).each(function() {
            var stuff = this.stuff;
            alert(stuff); // alerts 'stuffs'
            $(this.pages).each(function(key, value) {
                $.each(this, function(key, value) {
                    var pageName = key;
                    var pageUrl = value;
                    alert(pageName + ' ' + pageUrl);
                });
            });
        });
//    })
});

假设var json_data有您的数据,请根据需要替换.

Assuming var json_data having your data, Replace it as you need.

这篇关于如何从JSON对象中的数组获取键名及其值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

09-02 16:49