使用Object.keys从JavaScript中JSON文件中的值获取多维数组
根据问题(葡萄牙语),但他没有数组,我有数组。我应用了它,由于缺少他没有的数组,所以变量没有定义 您可以使用测试来运行预览 我还尝试应用以下问题:使用Object.keys从JavaScript中JSON文件中的值获取多维数组,javascript,html,arrays,json,Javascript,Html,Arrays,Json,根据问题(葡萄牙语),但他没有数组,我有数组。我应用了它,由于缺少他没有的数组,所以变量没有定义 您可以使用测试来运行预览 我还尝试应用以下问题: 首先在HTML文件中: 名称1 1岁 名称2 2岁 名称3 3岁 名称4 4岁 名称5 5岁 JSON: 基于葡萄牙语中的这个问题,例如: 函数readTextFile(文件,回调){ var rawFile=new XMLHttpRequest(); overrideMimeType(“application/json”); 打开
- 首先在HTML文件中:
1岁
名称22岁
名称33岁
名称44岁
名称55岁
- JSON:
- 基于葡萄牙语中的这个问题,例如:
- 或者使用对象键,例如:
readTextFile(“../json/people.json”),函数(文本){
var people=JSON.parse(文本);
var name=document.getElementById('name');
name.innerHTML=Object.keys(people.name).length;
var age=document.getElementById('age');
age.innerHTML=Object.keys(people.age).length;
console.log(人);
});
函数readTextFile(文件,回调){
var rawFile=new XMLHttpRequest();
overrideMimeType(“application/json”);
打开(“GET”,file,true);
rawFile.onreadystatechange=函数(){
if(rawFile.readyState==4&&rawFile.status==200){
回调(rawFile.responseText);
}
}
rawFile.send(空);
}
readTextFile(“https://pastebin.com/raw/CzxURs8y,函数(文本)
{
var people=JSON.parse(文本);
var name=document.getElementById('name');
name.innerHTML=people.name;
var age=document.getElementById('age');
age.innerHTML=people.age;
console.log(人);
});代码>
名称1
1岁
名称22岁
名称33岁
名称44岁
名称5age 5
元素id应始终是唯一的。尽管浏览器会使用重复的id值执行某些操作,但结果是不可预测的。这需要作为第一步进行修正。@JayB和@traktor53,问题是我的老师要求保留人员
,我不能更改JSON。您的JSON是一个对象,其中名为人员
的键包含您需要相应访问的数组,例如data=JSON.parse(text);data.people[0].name
@GustavoReis html元素id始终需要唯一(更改html,而不是json)您确定它支持inner.html吗?它几乎支持innerHTML,但不支持。太糟糕了。在HTML中,
,在JavaScript中:imageElms.forEach((n,i)=>{const product=json.products[i];let images=`;n.textContent.innerHTML=+images;})
n.innerHTML=images
{
"people":
[
{
"id": 0,
"name": "Person Name 0",
"age": 15
},
{
"id": 1,
"name": "Person Name 1",
"age": 25
},
{
"id": 2,
"name": "Person Name 2",
"age": 35
},
{
"id": 3,
"name": "Person Name 3",
"age": 45
},
{
"id": 4,
"name": "Person Name 4",
"age": 55
},
{
"id": 5,
"name": "Person Name 5",
"age": 60
}
]
}
fetch("../json/people.json")
.then(r=>r.json())
.then(json=>{
const nameElms = Array.from(document.querySelectorAll("[id='name']"));
const ageElms = Array.from(document.querySelectorAll("[id='age']"));
nameElms.forEach((n,i)=>{
const person = json.people[i];
n.textContent = person.name;
})
ageElms.forEach((n,i)=>{
const person = json.people[i];
n.textContent = person.age;
})
})