[英]Can't get data from a json object
我正在尝试 console.log 对象的“名称”。 每次我尝试这个它都会返回“未定义”。 我该如何解决这个问题?
fetch('http://localhost:9000/quiz/code', {
method: 'POST',
headers: {
'Accept': 'application/json',
'Content-Type': 'application/json',
},
body: JSON.stringify({
name: code
})
}).then(res => res.json())
.then(data => {
data = JSON.stringify(data);
console.log("data: " + data);
console.log("name: " + data.name);
})
这是我的第一个 console.log 的输出:
data: [{"_id":"5cab356c8b35014074855ada","name":"fsgsdfgd","vragen":{"vragen":[{"question":"Hoe wordt een middagdutje zoals dit bijvoorbeeld in Spanje wordt gehouden genoemd?","answer":"Een siësta","category":"Algemeen"},{"question":"Hoe wordt een middagdutje zoals dit bijvoorbeeld in Spanje wordt gehouden genoemd?","answer":"Een siësta","category":"Algemeen"}]}}]
这是我的第二个 console.log 的输出:
name: undefined
您在响应数据上使用stringify()
,然后将其视为对象。 那行不通。 只需删除data = JSON.stringify(data);
因为您已经拥有有效的 JSON(以数组的形式)。 您可以简单地遍历数组中的对象并获取每个对象的名称:
fetch('http://localhost:9000/quiz/code', {
method: 'POST',
headers: {
'Accept': 'application/json',
'Content-Type': 'application/json',
},
body: JSON.stringify({
name: code
})
}).then(res => res.json())
.then(data => {
console.log("data: ", data);
data.forEach(function(obj) {
console.log("name: " + obj.name);
});
console.log("name: " + data[0].name);
})
我删除了 JSON.stringify(data) 并将 data[0].name 添加到我的 console.log。 这解决了问题。 我的新代码如下所示:
fetch('http://localhost:9000/quiz/code', {
method: 'POST',
headers: {
'Accept': 'application/json',
'Content-Type': 'application/json',
},
body: JSON.stringify({
name: code
})
}).then(res => res.json())
.then(data => {
data = data;
console.log("name: " + data[0].name);
})
删除字符串化并使用 data[0].name
data = [{"_id":"5cab356c8b35014074855ada","name":"fsgsdfgd","vragen":{"vragen":[{"question":"Hoe wordt een middagdutje zoals dit bijvoorbeeld in Spanje wordt gehouden genoemd?","answer":"Een siësta","category":"Algemeen"},{"question":"Hoe wordt een middagdutje zoals dit bijvoorbeeld in Spanje wordt gehouden genoemd?","answer":"Een siësta","category":"Algemeen"}]}}] console.log(data[0].name)
//try like this
success: function (result) {
console.log(result);
show_edit_form();
$('#txt_order_id').val(result[0].rec_id);
$('#txt_first_name').val(result[0].fname);
$('#txt_last_name').val(result[0].lname);
},
数据:[{" 是数组
在按名称获取属性之前,您应该访问数组元素:
通过索引访问示例:
console.log("name: " + data[0].name);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.