jquery json路径

jquery json路径,jquery,json,Jquery,Json,我有下面的json { "id": "0001", "type": "donut", "name": "Cake", "ppu": 0.55, "batters": { "batter": [ { "id": "1001", "type": "Regular" }, { "id": "1002", "type": "Chocolate" }, {

我有下面的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作为变量传递

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

这不管用。有人能帮忙吗?

类似的东西应该能用(虽然我没有实际测试它):

// This won’t work:
var json_offset = 'topping.types';
var json_pointer = data.json_offset;
// Here, you attempt to read the `data` object’s `json_offset` property, which is undefined in this case.

// This won’t work either:
var json_offset = 'topping.types';
var json_pointer = data[json_offset];
// You could make it work by using `eval()` but that’s not recommended at all.

// But this will:
var offsetA = 'topping',
    offsetB = 'types';
var json_pointer = data[offsetA][offsetB];
然后,像这样使用它:

Object.getPath(data, json_offset)

但是,除非路径是动态的并且您不能,否则您应该只使用
data.topping.types
。另外,您将该路径称为“XPath”,但XPath是一个与您尝试执行的操作无关的非常不同的东西。

如果它是动态的,则类似的东西可以工作

var root = data;
var json_offset = 'topping.types';
json_offset = json_offset.split('.');

for(var i = 0; i < path.length - 1; i++) {
  root = root[json_offset[i]];
}

var json_pointer = root[path[json_offset.length - 1]];
var root=数据;
var json_offset='topping.types';
json_offset=json_offset.split('.');
对于(变量i=0;i
什么不起作用?你会得到什么错误?如果偏移量可变会发生什么?然后你会编写一个更通用的解决方案,就像@shesek在他的回答中所说的:)欢迎。我对它进行了一些编辑-不需要使用另一个
current
变量,它可以直接用
obj
完成,我添加了一个CoffeeScript版本只是为了检查一下
var root = data;
var json_offset = 'topping.types';
json_offset = json_offset.split('.');

for(var i = 0; i < path.length - 1; i++) {
  root = root[json_offset[i]];
}

var json_pointer = root[path[json_offset.length - 1]];