我试图从last.fm
中提取一些数据。
我收到以下回复:
{
"tracks": {
"track": [
{
"name": "Once Upon a Dream",
"duration": "203",
"loves": "738",
"mbid": "92078817-2e04-4bcd-9c43-ebb9c2d1823c",
"url": "http://www.last.fm/music/Lana+Del+Rey/_/Once+Upon+a+Dream",
"streamable": {
"#text": "0",
"fulltrack": "0"
},
"artist": {
"name": "Lana Del Rey",
"mbid": "b7539c32-53e7-4908-bda3-81449c367da6",
"url": "http://www.last.fm/music/Lana+Del+Rey"
},
"image": [
{
"#text": "http://userserve-ak.last.fm/serve/34s/96432461.png",
"size": "small"
},
{
"#text": "http://userserve-ak.last.fm/serve/64s/96432461.png",
"size": "medium"
},
{
"#text": "http://userserve-ak.last.fm/serve/126/96432461.png",
"size": "large"
},
{
"#text": "http://userserve-ak.last.fm/serve/300x300/96432461.png",
"size": "extralarge"
}
]
}
等等......
问题在于,当尝试访问回复的图像部分时,图像对象似乎有#text
作为我试图访问的信息的变量名称。正常response.tracks.track[i].image[0].text
显然不起作用。
有一些特殊的方法来访问这个变量吗?
答案 0 :(得分:3)
您可以使用the square bracket notation来访问该变量,如下所示:
response.tracks.track[i].image[0]['#text']
答案 1 :(得分:2)
它只是对象内部的一个关键名称。您无法通过点表示法访问它,因为它包含无效字符,但您可以使用括号表示法。这是一个非常简单的例子来证明这一点。
var foo = {
'#bar': 'http://www.google.com/'
}
foo['#bar'] // will return a string value of http://www.google.com/
如果您的密钥包含任何无效字符,则必须将其包含在字符串中。在您的情况下,您将获得一个JSON响应,该响应始终包含字符串包含的键名。
希望这有帮助!