I've got a JSON file that I have online that has some informations, like this:
{
"messages": [
{
"name": "info",
"content": [
{
"name": "Generic",
"fields": [
{
"name": "name1",
"content": "content1"
},
{
"name": "name2",
"content": "content2"
}
]
}
]
}
]
}
I am trying to put on an HTML page name1
and content1
.
How can I achieve that using JS?
I used fetch to get the data from the website and printing it to console shows it, but I don't know how to use it and how to put it inside my HTML page.
CodePudding user response:
Quick example of parsing a JSON string (if not already done), and accessing specific data. Note that in the real world you'd probably want to use some kind of loop to iterate over all the field.
const jsonString = '{"messages":[{"name":"info","content":[{"name":"Generic","fields":[{"name":"name1","content":"content1"},{"name":"name2","content":"content2"}]}]}]}';
const parsedObject = JSON.parse(jsonString);
const field1 = parsedObject.messages[0].content[0].fields[0];
document.querySelector('.name').textContent = field1.name
document.querySelector('.content').textContent = field1.content
<div ></div>
<div ></div>
CodePudding user response:
There are many ways this can be done (react,angular,vue) but since you asked JS, it can be put this way. you can use append function https://developer.mozilla.org/en-US/docs/Web/API/Element/append
const response = fetch('<enter url>')
let body = document.querySelector("body")
body.append(response[0].messages[0].content[0].fields[0].name)
body.append(response[0].messages[0].content[0].fields[0].content)
CodePudding user response:
It really depends on how you want to display that information. Here's an example that map
s over the data to create a table using template strings.
const data={messages:[{name:"info",content:[{name:"Generic",fields:[{name:"name1",content:"content1"},{name:"name2",content:"content2"}]}]}]};
// Destructure the `fields` array from the data
const { fields } = data.messages[0].content[0];
// This function accepts the fields array, and then
// `map`s over it to create a new array of table row HTML
// strings. The array of HTML strings in finally joined into
// one HTML string and returned from the function
function createRows(fields) {
return fields.map(field => {
return (`
<tr>
<td>${field.name}</td>
<td>${field.content}</td>
</tr>
`);
}).join('');
}
// Another template string creating HTML.
// This one defines the table and uses the HTML string
// returned from `createRows` to fill out the table body
const table = `
<table>
<thead>
<td>Name</td>
<td>Content</td>
</thead>
<tbody>${createRows(fields)}</tbody>
</table>`;
// Then add the final table HTML string to an element
// (in this case `document.body`)
document.body.innerHTML = table;
table { border-collapse: collapse; }
thead { background-color: #efefef; }
td { padding: 0.25em 0.5em; border: 1px solid #565656; }
Additional documentation