假设我有一些 JSON,如下所示:
{
"items":
{
"item":
[
{
"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" }
]
},
...
]
}
}
我想要一个函数来返回一个制表符分隔的数据列表(其中 -> 是一个制表符)。像这样的东西:
items.item.length -> 1
items.item[0].id -> 0001
items.item[0].type -> donut
items.item[0].name -> Cake
items.item[0].ppu -> 0.55
items.item[0].batters.batter.length -> 4
items.item[0].batters.batter[0].id -> 1001
items.item[0].batters.batter[0].type -> Regular
items.item[0].batters.batter[1].id -> 1002
items.item[0].batters.batter[1].type -> Chocolate
items.item[0].batters.batter[2].id -> 1003
items.item[0].batters.batter[2].type -> Blueberry
items.item[0].batters.batter[3].id -> 1004
items.item[0].batters.batter[3].type -> Devil's Food
items.item[0].topping.length -> 7
items.item[0].topping[0].id -> 5001
items.item[0].topping[0].type -> None
items.item[0].topping[0].id -> 5002
items.item[0].topping[0].type -> Glazed
...
我在想类似的东西
function json2txt(obj) {
var txt = '';
for (var key in obj) {
if (obj.hasOwnProperty(key)) {
if ("object" == typeof(obj[key])) {
json2txt(obj[key]);
} else txt += obj + '\t' + obj[key] + '\r';
}
}
}
“糟糕!您的编辑无法提交,因为:
您的帖子没有太多上下文来解释代码部分;请更清楚地解释你的情况。”
这也很令人沮丧。