gpt4 book ai didi

javascript/node JSON 解析问题

转载 作者:行者123 更新时间:2023-11-28 19:01:04 25 4
gpt4 key购买 nike

这是我的示例数据: http://api.setlist.fm/rest/0.1/setlist/4bf763f6.json

我只是编写一个 Node 应用程序来打印此页面的详细信息。我关心的是布景、布景和歌曲。

var sets = setlist.sets
res.write(JSON.stringify(sets)) // THIS SHOWS THE CORRECT DATA
var numSets = Object.keys(sets).length;
for(var i = 0; i < numSets; i++){
res.write("\nsets " + i);
var set = sets.set[i];
console.log(Object.getOwnPropertyNames(set))
var numSet = Object.keys(set).length;
res.write(JSON.stringify(set))
for(var j = 0; j < numSet; j++){
res.write("\nset " + (j+1) + " of " + numSet);
var song = set.song;
console.log(Object.getOwnPropertyNames(song))
numSong = Object.keys(song).length;
for(var k = 0; k < numSong; k++){
res.write("\n song " + j + "-" + k);
res.write("\n "+JSON.stringify(song[k]["@name"]));
}
}
}

我得到的是:

set 1 of 1
song 0-0
"Lift Me Up"
song 0-1
"Hard to See"
song 0-2
"Never Enough"
song 0-3
"Got Your Six"
song 0-4
"Bad Company"
song 0-5
"Jekyll and Hyde"
song 0-6
"Drum Solo"
song 0-7
"Burn MF"
song 0-8
"Wrong Side of Heaven"
song 0-9
"Battle Born"
song 0-10
"Coming Down"
song 0-11
"Here to Die"

集合中有两个歌曲元素:(抱歉没有代码块,否则它不会换行)

{
"set": [{
"song": [{
"@name": "Lift Me Up"
}, {
"@name": "Hard to See"
}, {
"@name": "Never Enough"
}, {
"@name": "Got Your Six"
}, {
"@name": "Bad Company",
"cover": {
"@disambiguation": "British blues-rock supergroup",
"@mbid": "0053dbd9-bfbc-4e38-9f08-66a27d914c38",
"@name": "Bad Company",
"@sortName": "Bad Company",
"@tmid": "734487",
"url": "http://www.setlist.fm/setlists/bad-company-3bd6b8b0.html"
}
}, {
"@name": "Jekyll and Hyde"
}, {
"@name": "Drum Solo"
}, {
"@name": "Burn MF"
}, {
"@name": "Wrong Side of Heaven",
"info": "Acoustic"
}, {
"@name": "Battle Born",
"info": "Acoustic and Electric"
}, {
"@name": "Coming Down"
}, {
"@name": "Here to Die"
}]
}, {
"@encore": "1",
"song": [{
"@name": "Under and Over It"
}, {
"@name": "Burn It Down"
}, {
"@name": "The Bleeding"
}]
}]
}

在 Swift 中,我只需设置一个字典,它就可以正常工作。 JavaScript 不是我的强项。为什么我无法获取第二首歌曲元素?

最佳答案

setlist.set 是一个由两个对象组成的数组,一个包含“常规”(?)歌曲,另一个包含安可信息。

看起来您将循环变量与其他对象/数组混合在一起,并且没有迭代您认为正在迭代的内容。

这是一个简化版本,应该显示您所期望的内容:

// `sets` is an object containing (at least) `set` and `url` properties
var sets = setlist.sets;

// `set` is an array containing (in your example, two) objects
var set = sets.set;

for (var i = 0; i < set.length; ++i) {
console.log('Set %d/%d', i+1, set.length);

// `curSet` is an object containing a `song` property
var curSet = set[i];

// `songs` is an array of objects
var songs = curSet.song;

for (var j = 0; j < songs.length; ++j) {
// `song` is an object containing properties like `@name` and possibly others
var song = songs[j];

console.log(' - Song: %s', song['@name']);
}
}

关于javascript/node JSON 解析问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32534511/

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