A guide on extracting data from a JSON string and populating a list in JavaScript

Is there a way for me to extract the "Toppings" values from my JSON string and display them as list items? I appreciate any assistance you can provide!

<html>
<body>

<section>
<h2>Toppings</h2>
<ul>
    <li>JSON String Value </li>
    <li>JSON String Value </li>
    <li>JSON String Value </li>
    <li>JSON String Value</li>
</ul>
</section>

     </body>
<script>
var myObj ={"menu": {"slice of pizza": "2.00", "toppings": {"pepperoni": ".25","meatballs": ".35", "mushrooms": ".40","olives": ".20"},"sides": {"potato salad": "1.25","hummus": "2.50","caesar salad": "3.50","garden salad": "2.25"},   "drinks": { "soda": {   "small": "1.95",  "medium": "2.20","large": "2.50" }, "juice": "2.00", "water": "1.25"}}};
var myJSON = JSON.stringify(myObj);
</script>

</html>

Answer №1

Check out this code solution below

try using this snippet

<html>
<body>

<section>
<h2>Toppings</h2>
<ul id="serveJson">
</ul>
</section>

     </body>
<script>
var myObj ={"menu": {"slice of pizza": "2.00", "toppings": {"pepperoni": ".25","meatballs": ".35", "mushrooms": ".40","olives": ".20"},"sides": {"potato salad": "1.25","hummus": "2.50","caesar salad": "3.50","garden salad": "2.25"},   "drinks": { "soda": {   "small": "1.95",  "medium": "2.20","large": "2.50" }, "juice": "2.00", "water": "1.25"}}};

var toppings = myObj.menu.toppings;

var ul = document.getElementById('serveJson');
for(name in toppings)
{
    var li = document.createElement('li');
    li.appendChild( document.createTextNode(toppings[name]) );
    ul.appendChild(li);
}

</script>

</html>

Answer №2

To extract the keys from the Toppings object, use Object.keys method in combination with forEach loop to dynamically create list items and populate an unordered list. Make sure to assign an ID to your ul element:

let toppingsKeys = Object.keys(myObj.menu.toppings);
let ulElement = document.getElementById("yourUlId");

toppingsKeys.forEach(function(key) {
       let liItem = document.createElement("LI");
       let textNode = document.createTextNode(key); 
       liItem.appendChild(textNode);
       ulElement.appendChild(liItem);
});

Answer №3

If you already have the li defined, you can experiment with this approach:

var myObj ={"menu": {"slice of pizza": "2.00", "toppings": {"pepperoni": ".25","meatballs": ".35", "mushrooms": ".40","olives": ".20"},"sides": {"potato salad": "1.25","hummus": "2.50","caesar salad": "3.50","garden salad": "2.25"},   "drinks": { "soda": {   "small": "1.95",  "medium": "2.20","large": "2.50" }, "juice": "2.00", "water": "1.25"}}};

var myJSON = Object.keys(myObj.menu.toppings);
var allLI = document.querySelectorAll('ul > li');
allLI.forEach(function(li, i){
  li.textContent = myJSON[i] + ': ' + myObj.menu.toppings[myJSON[i]];
});
<section>
<h2>Toppings</h2>
<ul>
    <li>JSON String Value </li>
    <li>JSON String Value </li>
    <li>JSON String Value </li>
    <li>JSON String Value</li>
</ul>
</section>

Answer №4

Here is a solution I came up with :)

var ul = document.getElementsByTagName('ul')[0];
var myObj ={"menu": {"slice of pizza": "2.00", "toppings": {"pepperoni": ".25","meatballs": ".35", "mushrooms": ".40","olives": ".20"},"sides": {"potato salad": "1.25","hummus": "2.50","caesar salad": "3.50","garden salad": "2.25"},   "drinks": { "soda": {   "small": "1.95",  "medium": "2.20","large": "2.50" }, "juice": "2.00", "water": "1.25"}}};

Object.keys(myObj.menu.toppings).forEach((key) => {
    var li = document.createElement('li');
    li.innerText = `${key}: ${myObj.menu.toppings[key]}`;
    ul.append(li);
});

And here is the result:

<ul>
    <li>pepperoni: .25</li>
    <li>meatballs: .35</li>
    <li>mushrooms: .40</li>
    <li>olives: .20</li>
</ul>

Answer №5

Give this a try

<!DOCTYPE html>
    <html>
    <body>

    <h2>Change a JavaScript object to a JSON string, then transmit it to the server.</h2>

    <script>

    var myObj = {"menu": {"slice of pizza": "2.00", "toppings": {"pepperoni": ".25","meatballs": ".35", "mushrooms":   ".40","olives": ".20"},"sides": {"potato salad": "1.25","hummus": "2.50","caesar salad": "3.50","garden salad": "2.25"},     "drinks": { "soda": {   "small": "1.95",  "medium": "2.20","large": "2.50" }, "juice": "2.00", "water": "1.25"}}};
    var myj=JSON.parse(JSON.stringify(myObj));
    console.log(myj.menu.toppings);


    </script>

    </body>
    </html>

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

The animated loading image is taking an eternity to actually load

My website is loaded with heavy front-end features and I'm using a loading gif to help with the loading process. However, I've noticed that in Safari, there is a delay before the gif loads after the background does, which takes away from the inte ...

Setting up Django model form using jQuery and JavaScript

In my project, I am working with three different models: class Instances(models.Model): name_of_instances = models.CharField(max_length=255) url_of_instances=models.URLField(max_length=255,default='') def __str__(sel ...

Tips on locating information within a pre-existing GET array with parameters provided

Apologies for the unclear title. I am currently utilizing a category chooser that pulls categories from an API. The process involves fetching a list of categories, filtering out their names, and presenting them in the category chooser. Upon clicking submit ...

Updating existing objects in json using the google-http-java-client

Currently, I am attempting to utilize the google-http-java-client library on an Android platform to parse JSON responses from my server. To achieve this, I have implemented the code provided in the project examples. private static final HttpTransport ...

Finding a workaround for the absence of a leftToggle feature in ListItem component of Material-UI

Is there a way to move the toggle element to the other side in Material-UI's listItem without using the leftToggle option? The documentation does not specify a leftToggle attribute, so I am looking for alternative solutions. I would like to align the ...

A method that sorts an array of objects based on their properties

I am currently working with two specific objects: clinics: [ { id: 1, name: 'New Hampshire Veterinarian Clinic', plans: [ 'handle123', 'handle567', ] }, { ...

Struggling to make the upvoting feature function properly in the Thinkster MEAN Stack Tutorial

While following the MEAN Stack tutorial on this website, I decided to modify my code to utilize Controller as instead of using $scope as demonstrated in their examples. I am encountering an issue with the upvote functionality. Whenever I click to upvote a ...

Tips for modifying a request api through a select form in a REACT application

Apologies if this question seems a bit basic, but I need some help. I am working on creating a film catalog using The Movie Database API. I have successfully developed the home and search system, but now I am struggling to implement a way to filter the fi ...

Is a String the data type of a list when passed to the Controller from GSP?

Within my Javascript code on the client side, I have constructed a List of Strings that appears in the Javascript console like this: ["No address provided.", "No telephone number provided."] When I send this data to my Controller as one of the parameters ...

Load the Google Maps JavaScript file only when it is required

I am working on a page that contains a button to open Google Maps in a modal. Since this function is rarely used by users, I am exploring the possibility of loading the Google Maps library only when it is needed. I would rather have the user wait for the m ...

The index appears multiple times when navigating through the prev/next pagination

How can I prevent the repetition of index values when switching between previous and next buttons while displaying 15 posts each time? For example, currently when clicking on the next button and reaching an index value of 5, then clicking on prev shows th ...

Loading the Facebook JavaScript SDK asynchronously using React and Redux

I have a process that involves loading a JavaScript SDK, which looks like this: class Facebook{ constructor(){ window.fbAsyncInit = () => { FB.init({ appId : 'myappID', ...

Would this code effectively disable the right-clicking menu for MathJax?

My current approach involves utilizing the following code snippet: <script type="tet/x-mathjax-config"> MathJax.Hub.Config({ showMathMenu: false }); </script> I intended for this code to disable the right-click menu on my math webs ...

Using double quotation marks in Node.js to enclose variables

How do I pass variables from a post route redirect to a get route in Express? Thank you for your help. router.post("/message", function(req, res) { var email = req.body.email; res.redirect(`/passingemail/${email}`); }); //I want to retrieve the ...

Is the background color change function with AJAX not functioning properly when using array values?

Let me simplify my issue. I have an AJAX call to fetch a JSON array with "aht_value". Based on this value, I am creating a color gradient from green to red (creating a heat map). The values are being output correctly. The issue: The problem lies within m ...

dynamically filter a set of string elements

Is there a way to dynamically filter a list of strings? I have come across examples using ng-repeat, but it seems that it does not work with angular 7: it does not load any strings, only works with ngFor <div class="input-group"> <div class="i ...

Scala Play - Efficient strategy for transferring large data using HTTP requests

Seeking guidance on transmitting sizable datasets via Play WS. I am performing computations on a binary file resulting in a Map[String, List[Double]] that I wish to send using a HTTP POST. The List<Double> includes points from the binary file. Initia ...

What are the advantages of using the CRUD coding style with Redux?

Seeking guidance on the best coding style for a single page application regarding the use of React Redux For instance, consider a standard CRUD page where data is presented in a table with a pop-up modal form. The table's data comes from server-side ...

Struggling with accessing specific data from JSON response when using Alamofire in Swift

I'm currently facing an issue with accessing the response json data in the code below. Snapshot 1: https://i.sstatic.net/MBDH1.png Snapshot 2: https://i.sstatic.net/InQ14.png The response json I receive seems to have "()" after the key "bookings" ...

What is the best way to transform an Array into Json format using Java?

I'm in need of converting an Array into a Json Object, akin to this: String[] items = {"item1", "item2"}; The goal is to transform it into: { "items": ["item1", "item2"] } I am currently working with Spring (Jackson XML). This was my attempt: ...