jQuery JSON路径 [英] jquery json path

查看:67
本文介绍了jQuery JSON路径的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有以下json

{
    "id": "0001",
    "type": "donut",
    "name": "Cake",
    "ppu": 0.55,
    "batters": {
        "batter": [
                { "id": "1001", "type": "Regular" },
                { "id": "1002", "type": "Chocolate" },
                { "id": "1003", "type": "Blueberry" },
                { "id": "1004", "type": "Devil's Food" }
            ]
    },
    "topping": [
        { "id": "5001", "type": "None" },
        { "id": "5002", "type": "Glazed" },
        { "id": "5005", "type": "Sugar" },
        { "id": "5007", "type": "Powdered Sugar" },
        { "id": "5006", "type": "Chocolate with Sprinkles" },
        { "id": "5003", "type": "Chocolate" },
        { "id": "5004", "type": "Maple" }
    ]
}

我正在尝试将xpath作为变量传递.

I am trying to pass an xpath as a variable.

$(document).ready(function(){
    var json_offset = 'topping.types'
    ...
    $.getJSON('json-data.php', function(data) {
        var json_pointer = data.json_offset;
        ...
    });
});

不起作用.有人可以帮忙吗?

Which dosn't work. Can anyone help?

推荐答案

类似的方法应该可以工作(我实际上没有对其进行测试):

Something like that should work (I didn't actually test it, tho):

Object.getPath = function(obj, path) {
    var parts = path.split('.');
    while (parts.length && obj = obj[parts.shift()]);
    return obj;
}
// Or in CoffeeScript:
// Object.getPath = (obj, path) -> obj=obj[part] for part in path.split '.'; obj

然后,像这样使用它:

Object.getPath(data, json_offset)

但是,除非路径是动态的并且您不能这样做,否则应该只使用data.topping.types.另外,您将该路径称为"XPath",但是XPath是完全不同的东西,与您尝试执行的操作无关.

However, unless the path is dynamic and you can't, you should simply use data.topping.types. Also, you referred to that path as "XPath", but XPath is a very different thing that has nothing to do with you're trying to do.

这篇关于jQuery JSON路径的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆