[英]Get Child JSON Values from Objects
I have an endpoint with two JSON Objects as follows: 我有一个带有两个JSON对象的端点,如下所示:
{
"main" {
"id": 1,
"title": Main Title,
},
{
"secondary" {
"id": 3,
"title": Secondary Title,
},
I am using backbone and have the following $each function, but using dot notation, I can't seem to be able to browse to the titles (ex. main.title or secondary.title). 我使用的是骨干网,并且具有以下$ each函数,但是使用点符号,我似乎无法浏览标题(例如main.title或secondary.title)。 What am I missing? 我想念什么?
var collection = new contentArticles([], { id: urlid });
collection.fetch({
dataType: "json",
success: function (model, response) {
console.log(response);
$.each(response, function (index, value) {
console.log(value.main.title);
$("#test2").append('<li>' + value.main.title + '</li>');
});
In my console, it gives an error of: Uncaught TypeError: Cannot read property 'title' of undefined 在我的控制台中,它给出以下错误:Uncaught TypeError:无法读取未定义的属性“ title”
Assuming your JSON is actually valid when returned (it isn't valid the way you show it), try 假设您的JSON在返回时实际上是有效的(显示方式无效),请尝试
$("#test2").append('<li>' + value.title + '</li>');
Your actual JSON should look like: 您的实际JSON应该如下所示:
{
"main": {
"id": 1,
"title": Main Title,
},
"secondary": {
"id": 3,
"title": Secondary Title,
}
}
If you just want the value of main, instead of using $.each(), remove that entire block and do: 如果只需要main的值,而不是使用$ .each(),则删除整个块并执行以下操作:
$("#test2").append('<li>' + response.main.title + '</li>');
And your final code would look something like: 您的最终代码如下所示:
var collection = new contentArticles([], { id: urlid });
collection.fetch({
dataType: "json",
success: function (model, response) {
console.log(response);
if (response.main.title !== 'undefined'){
$("#test2").append('<li>' + value.main.title + '</li>');
}else{
console.log('Main is undefined');
}
}
});
Final Edit: It looks like you want JSON like: 最终编辑:看起来像您想要JSON一样:
{
"main": [{
"id": 1,
"title": "Main Title"
}, {
"id": 2,
"title": "Main Title 2"
}, {
"id": 3,
"title": "Main Title 3"
}],
"secondary": [{
"id": 5,
"title": "Secondary Title 5"
}, {
"id": 34,
"title": "Secondary Title 34"
}, {
"id": 36,
"title": "Secondary Title 36"
}]
}
If that is the case your code would look like: 如果是这种情况,您的代码将如下所示:
var collection = new contentArticles([], { id: urlid });
collection.fetch({
dataType: "json",
success: function (model, response) {
console.log(response);
$.each(function(index, value){
$.each(item_index, item_value){
$("#test2").append('<li>' + item_value.title + '</li>');
}
});
}
});
The problem lies with input JSON, it should be 问题在于输入JSON,应该是
{
"main" :{
"id": 1,
"title": "Main Title"
},
"secondary":{
"id": 3,
"title": "Secondary Title"
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.