2011-09-05 76 views
2

我有以下的JSONjQuery的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; 
     ... 
    }); 
}); 

哪个工作没有效果。谁能帮忙?

+0

什么不行?你会得到什么错误? –

回答

3

类似的东西应该工作(我没有实际测试,寿):

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与您尝试执行的操作完全不同。

+0

感谢那正是我之后的。 –

+0

欢迎你。我编辑了一下 - 没有必要使用另一个'current'变量,它可以直接用'obj'完成,并且我添加了一个CoffeeScript版本 – shesek

3
// 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]; 
+0

@ mathias非常感谢你! –

+0

如果我有可变数量的偏移,会发生什么情况? –

+0

然后你写一个更通用的解决方案,就像@shesek在他的回答中所说的那样:) –

1

像这样的东西如果是动态的,

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]];