asked on
Help displaying JSON in HTML
I'm experimenting to learn JavaScript.
Please help me understand why the code examples below worked or didn't work.
I start with a simple html page in one file and in a different file (menu.json) I have some JSON. I tried various codes within the script tag to retrieve the JSON and display it:
<!DOCTYPE html>
<html lang="en">
<head>
<!-- meta tags removed for clarity -->
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.6.1/jquery.min.js"></script>
<script>
$(document).ready(function () {
// tried various codes here
});
</script>
</head>
<body>
<div>here</div>
</body>
</html>
My goal is to get the JSON to appear within the <div> tags and replace the word, here.
This code worked as expected:
$(document).ready(function () {
$("div").load("menu.json");
});
The word, "here" was replaced with the JSON,
{ "menu": { "id": "file", "value": "File", "popup": { "menuitem": [ { "value": "New", "onclick": "CreateNewDoc()" }, { "value": "Open", "onclick": "OpenDoc()" }, { "value": "Close", "onclick": "CloseDoc()" } ] } } }
This code also worked as expected:
$(document).ready(function () {
$.getJSON("menu.json", function (data) {
console.log(data);
});
});
The menu JSON appeared in the console.
So, I expected that any of the below would also work:
$.getJSON("menu.json", function (data) {
$("div").text(data); // [object Object]
$("div").text(JSON.parse(data)); // did nothing
$("div").val(data); // did nothing
$("div").append(data); // did nothing
});
None of those worked. The closest was,
$("div").text(data); // [object Object]
This also worked for the console:
$.getJSON("menu.json", function (result) {
$.each(result, function (i, field) {
console.log(field);
});
});
But failed for the <div> tag:
$.getJSON("menu.json", function (result) {
$.each(result, function (i, field) {
$("div").append(field);
});
});
I tried many other things, but to keep it less lengthy, I only showed a few.
Please help me understand how I can make this goal work and also explain why the code I tried failed.
Thanks in advance.
ASKER
I got that JSON at a site with examples. I just randomly picked it.
I'm not sure what your code is doing. That's the sort of code I want to eventually understand. But for now, it can't be that complicated to take the contents of a file and put it inside a div tag. The .load() function did it with one step. Outputting it to the console is also quick.
Suppose it was a simpler JSON like,
{"x": "y"}
I was able to get the letter y in the div tags with this:
$.getJSON("simple.json", function (result) {
$.each(result, function (i, field) {
$("div").append(field);
But I wanted to get the whole thing in there.
I don't understand why none of these uncommented work:
$.getJSON("simple.json", function (data) {
// $("div").text(data); // [object Object]
// $("div").text(JSON.parse(data)); // did nothing
// $("div").text(JSON.stringify(data)); // did nothing
// $("div").val(data); // did nothing
// $("div").append(data); // did nothing
});
The closest to working was
$("div").text(data);
but that only gave me [object Object]
Maybe I can get the value out of that and put it in the div?
ASKER
The only one that worked was:
$("div").text(JSON.stringify(data));
Even this did not work:
$(document).ready(function () {
$.getJSON("menu.json", function (data) {
console.log(JSON.parse(data));
});
I tried with two JSON files.
simple.json:
{"x": "y"}
and
menu.json:
{
"menu": {
"id": "file",
"value": "File",
"popup": {
"menuitem": [
{ "value": "New", "onclick": "CreateNewDoc()" },
{ "value": "Open", "onclick": "OpenDoc()" },
{ "value": "Close", "onclick": "CloseDoc()" }
]
}
}
}
I'm curious why the other two didn't work.
After this, I will learn how to parse out individual parts of the JSON.
delivers an object, so
JSON.parse(data) will not work.
JSON.stringify WILL work as you saw
When you have received an object from
- fetch plus response.jons() or
- from getJSON or
- when you have JSON.parsed a JSON string
{"x":"y"} is a very simple object and has just a key and a value, so very easy to manipulate
THIS object is a nested object
{ // in your case data object
"menu": { // an object
"id": "file", // a key:value pair
"value": "File", // a key:value pair
"popup": { // a key:object
"menuitem": [ // a key: array (also an object) with 3 items
{ "value": "New", "onclick": "CreateNewDoc()" }, // an object with two key:value pairs
{ "value": "Open", "onclick": "OpenDoc()" }, // an object with two key:value pairs
{ "value": "Close", "onclick": "CloseDoc()" } // an object with two key:value pairs
] // end of menuitem array
} // end of popup object
} // end of menu object
} // end of data object
Depending on what you need, you may need to parse/iterate the object using a recursive functionFor example
https://jsfiddle.net/mplungjan/oLmw916u/
const keys = [], findKeys = (object, prevKey = '') => {
Object.entries(object).forEach(([key,value]) => {
const nestedKey = prevKey === '' ? key : `${prevKey}.${key}`;
if (typeof object[key] !== 'object') return keys.push(`${nestedKey}:${value}`); // not an object
findKeys(object[key], nestedKey); // recurse
});
};
findKeys(result); // fill the keys array
console.log(keys.join("\n")); // display it
which produces
menu.id:file
menu.value:File
menu.popup.menuitem.0.value:New
menu.popup.menuitem.0.onclick:CreateNewDoc()
menu.popup.menuitem.1.value:Open
menu.popup.menuitem.1.onclick:OpenDoc()
menu.popup.menuitem.2.value:Close
menu.popup.menuitem.2.onclick:CloseDoc()
I could not really guess what your menu would look like since you have strange value entries which only input fields and buttons have.
Here is an attempt that is not very menu-like. Please add some expected HTML for me to work on
https://jsfiddle.net/mplungjan/4pv1jewt/
Open in new window