我真的迷上了如何访问从我的api获取的json响应的嵌套元素。我验证了json,并显示为有效。
例如,如何访问numFound属性?这是我的无效代码:
$.ajax({
url: "/api/SearchAPI/infopop?id=" + songID,
datatype:"json",
method: "get"
}).done(function (data) {
var obj = JSON.parse(data);
alert(obj); /* This displays the entire json response
alert(obj.response.numFound) /* This does not work
alert(data.response.numFound) /* This does not work
这是我要访问的回复
{
"responseHeader":{
"status":0,
"QTime":0,
"params":{
"q":"*:*",
"indent":"off",
"fl":"Name,Description,Keywords,ISRC,Instruments,Lyrics,Bpm,Vocal,Tempo,Key,TV_Genres,Music_Genres,length\r\n,Writers,profileImagePath\r\n,Publishers\r\n,songImagePath\r\n,Band_Styles",
"start":"0",
"callback":"?\r\n",
"fq":[
"id:00106c8c-7e21-4e75-80da-cdff8e6d3d44",
"publicflag:1",
"pubname:komposed"
],
"rows":"10",
"version":"2.2",
"wt":"json"
}
},
"response":{
"numFound":1,
"start":0,
"docs":[
{
"profileImagePath":[
"https://komposed.blob.core.windows.net/jrock-1873564a-d409-4370-80d8-23dc97114f18/songimage/f557110f-4ad3-4353-a1b3-3ba70d52e8f0?sv=2014-02-14&sr=b&sig=Q3ywrwEa6URp%2FPCvK0Ngesza8PBhMEmE5ONeKhw8vE4%3D&st=2016-06-16T16:49:45Z&se=2066-06-16T16:54:45Z&sp=r&rsct=application%2Foctet-stream&rscd=attachment%3B%20filename%3Dredneck.jpeg"
],
"songImagePath":[
"https://komposed.blob.core.windows.net/jrock-1873564a-d409-4370-80d8-23dc97114f18/songimage/f0c00dcd-69f9-42af-b236-4a53f0d78e76?sv=2014-02-14&sr=b&sig=oF0STMDddyuJiNZO%2BE78sYtbboC4ic%2Fl4bR5ESBFouE%3D&st=2016-06-16T16:48:59Z&se=2066-06-16T16:53:59Z&sp=r&rsct=application%2Foctet-stream&rscd=attachment%3B%20filename%3DTENSION%20LAST%20MAN.jpg"
],
"Name":[
"Bottle Service Tension"
],
"Description":[
"Cool crime scene track with a chill night club vibe"
],
"Bpm":[
90
],
"Vocal":[
"Acapella"
],
"Tempo":[
"Fast"
],
"Writers":[
"Justin Sirota|100.00|"
],
"Keywords":[
"club, crime, investigation, cool, lounge, pulse"
],
"TV_Genres":[
"Tension"
]
}
]
}
}
答案 0 :(得分:0)
只需使用obj.numFound
。 response
是您的data
参数。
$.ajax({
...
}).done(function (response) {
alert(response.numFound)
...
此外,由于您通过datatype:"json",
告诉jQuery(假设基于代码),响应是JSON类型,因此您无需对其进行JSON.parse
。
答案 1 :(得分:0)
原来问题出在我的API中。我将json作为字符串而不是对象返回。一旦这样做,javascript就可以引用json元素。感谢您的帮助!