简体   繁体   English

如何在js中显示来自json的对象

[英]How to display object from json in js

I have json code我有json代码

{
    "dezui": {
        "title": "DezUI CSS Framework",
        "description": "",
        "organizer": [""],
        "status": true,
        "homepage": "",
        "link": [""],
        "date": [18, 10, 2021],
        ...
    },
    ...
}

I want to display with loop in my page.我想在我的页面中循环显示。 Previous json code:之前的json代码:

{
    "portfolio": [
        {
            "title": "DezUI CSS Framework",
            "description": "",
            "organizer": [""],
            "status": true,
            "homepage": "",
            ...
        },
        ...
    ]
}

With the previous code, I display the data with the code below:使用前面的代码,我使用以下代码显示数据:


fetch("/portfolio/portfolio.json")
.then(response => {return response.json()})
.then(data => {
    for (let i = 0; i < data.portfolio.length; i++) {
        if (data.portfolio[i].status == true) {
            document.getElementById("portfolio").innerHTML += `<div id="card-project"><div id="thumbnail"><a href="/portfolio/${data.portfolio[i].homepage}"><img src="/portfolio/thumbnails/${data.portfolio[i].thumbnail}"></a></div><h6 id="tag">${data.portfolio[i].tag}</h6><h6 id="title"><a href="/portfolio/${data.portfolio[i].homepage}">${data.portfolio[i].title}</a></h6></div>`
        }
    }
})

I'm confused how I display in the form of an object(?)我很困惑我如何以对象的形式显示(?)

Please help me请帮我

Since your data shape changed you'll need to update your code.由于您的数据形状已更改,因此您需要更新代码。 You no longer need to loop through it as there is only one entry.您不再需要遍历它,因为只有一个条目。 So you can reference that object and change it from portfolio to dezui .因此,您可以引用该对象并将其从portfolio更改为dezui ex:前任:

fetch("/portfolio/portfolio.json")
    .then(response => {return response.json()})
    .then(data => {
        if (data.dezui.status == true) {
            document.getElementById("portfolio").innerHTML += `<div id="card-project"><div id="thumbnail"><a href="/portfolio/${data.dezui.homepage}"><img src="/portfolio/thumbnails/${data.dezui.thumbnail}"></a></div><h6 id="tag">${data.dezui.tag}</h6><h6 id="title"><a href="/portfolio/${data.dezui.homepage}">${data.dezui.title}</a></h6></div>`
    }
})

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM