使用json结果并使用字符串作为键

时间:2013-10-15 04:06:03

标签: javascript jquery json

我正在尝试使用不使用数字作为键但字符串

的json数据集

这使得返回结果变得有点复杂。

所以如果json结构是这样的

{
    "total": 1,
    "data": {
        "tab": {
            "what-you-doing": {
                "tabColWidth": "2",
                "tabColHeight": "2",
                "category": "CategoryA",

            },
            "tab-smaller-78e": {
                "tabColWidth": "1",
                "tabColHeight": "1",
                "category": "CategoryB",

            }
        }
    }
}

然后我想查询这个

我的js to getJson

function getJSON (name, path) {


var promise =   $.ajax({
        url: path + name + '.json',
        method: 'get',
        dataType: 'json'
});

return promise;
}

然后使用数据集

$(document).ready(function(){

    var promise = getJSON('feed', "../data/");

    $.when(promise).then(function(result) {

        $(result.data.tab).each(function(index, element) {

        console.log(element);

        console.log(element['what-you-doing'].category);

        });
    });

显然我不想在代码中指定你做什么,所以如何在这个循环中获得这个名字,并查看它下面的结果。

在json中不使用[]的原因是为了更容易找到这个结果而不必再进行另一个循环。
    });

1 个答案:

答案 0 :(得分:2)

您是否在询问如何在javascript中循环对象中的键?因为JSON被转换为javascript对象......你可能只需要

for (var key in element) {
    console.log(key);
    console.log(element[key]);
}