InterSet Ltd

Display / Parse nested JSON data using JavaScript (Live Demo)

Nested JSON Data Using JavaScript

Share Now:

Share on facebook
Share on linkedin
Share on twitter
Share on email
0 0 vote
Article Rating

To implement it yourself, you could write a recursive function. If the element you’re about to print is an array or object, you want to make a recursive call and print out that item’s contents.

Basically, if we ever call the function, we’re expecting to get back a new ul element, so we create one at the start and append to it.

Then, we loop over each of the items in the given object. It could be an array, another object, or just a string, integer, or other primitive.

In each iteration, we want to create a new li. Then, we append the key (for arrays, it’s the index; for objects, it’s your specified key when instantiating the object). And finally, we check if the item we want to print is another object (the typeof an array evaluates to object, so it works for arrays, too). If it is, we call the function recursively on the object to get the ul for that.

If not, we just append the text node for the item itself.

Be aware that if you’re fetching this data from some sort of API, there may be more than one object present in this array in future fetches, and the first element (index 0) may not be the one you’re looking for.

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="utf-8">
    <title>Parse Nested JSON Data in JavaScript</title>
</head>
<body>
    <script>
    /* Storing multi-line JSON string in a JS variable
    using the new ES6 template literals */
    var json = `{
        "book": {
            "name": "Harry Potter and the Goblet of Fire",
            "author": "J. K. Rowling",
            "year": 2000,
            "characters": ["Harry Potter", "Hermione Granger", "Ron Weasley"],
            "genre": "Fantasy Fiction",
            "price": {
                "paperback": "$10.40", "hardcover": "$20.32", "kindle": "$4.11"
            }
        }
    }`;
    
    // Converting JSON object to JS object
    var obj = JSON.parse(json);
    
    // Define recursive function to print nested values
    function printValues(obj) {
        for(var k in obj) {
            if(obj[k] instanceof Object) {
                printValues(obj[k]);
            } else {
                document.write(obj[k] + "<br>");
            };
        }
    };
    
    // Printing all the values from the resulting object
    printValues(obj);
    
    document.write("<hr>");
    
    // Printing a single value
    document.write(obj["book"]["author"] + "<br>");  // Prints: J. K. Rowling
    document.write(obj["book"]["characters"][0] + "<br>");  // Prints: Harry Potter
    document.write(obj["book"]["price"]["hardcover"]);  // Prints: $20.32
    </script>
</body>
</html>                            
0 0 vote
Article Rating
Subscribe
Notify of
0 Comments
Inline Feedbacks
View all comments

Get Free Access to InterSet’s 1 GB SSD Hosting with Website Design


Know Your

interset app coming soon

More You Would be interested in . . .

Have you any Question ?
Ask us !

0
Would love your thoughts, please comment.x
()
x