2011-09-05 5 views
2

은 내가 변수로는 XPath를 전달하는 데 노력하고JQuery와 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" } 
    ] 
} 

다음 JSON을 가지고있다.

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