2011-09-05 74 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]];