gpt4 book ai didi

jquery json 路径

转载 作者:行者123 更新时间:2023-12-01 02:35:19 24 4
gpt4 key购买 nike

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

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

最佳答案

类似的东西应该可以工作(我实际上没有测试它):

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 是一个非常不同的东西,与您想要做的事情无关。

关于jquery json 路径,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7305832/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com