5

First time being exposed to JSON so please explain like I'm 5 without the jargon. I have been given a JSON file like this and need to display these items in a list in HTML. A lot of examples have the JSON object assigned to a variable- this isn't assigned to a variable so I'm unsure how to reference it. How can I access and display everything in product list. In my html I have linked to a script.js file and also this json file.

HTML

  <h1>My Cart</h1>
    <div id="cart">
        <h2>Cart Items</h2>
        <ul id="cartItemsList">
        </ul>
    </div>

JSON

    "basket": {
        "productList": [{
            "product": {
                "id": "111",
                "name": "Dog",
                "shortDescription": "<p>Mans best friend</p>",
                },
                "category": "Canine",
                "availability": "In Stock",
                "variationType": {
                    "name": "Breed",
                    "value": "Collie"
                }
            },
            "quantity": 1,
            "price": "$53.00"
        }, {
            "product": {
                "id": "112",
                "name": "Dog",
                "shortDescription": "<p>Not so best friend</p>",
                "category": "feline",
                "availability": "Low In Stock",
                "variationType": {
                    "name": "breed",
                    "value": "Maine Coon"
                }
            },
            "quantity": 1,
            "price": "$49.00"
        }, {
            "product": {
                "id": "113",
                "name": "Rabbit",
                "shortDescription": "Likes carrots",
                "category": "cuniculus",
                "availability": "In Stock"
            },
            "quantity": 1,
            "price": "$66.00"
        }]
    }

JavaScript

    var products = document.getElementById("cartItemsList");
    cartItemsList.innerHTML = "<li>" + product + "</li>";
1

5 Answers 5

6

If you are loading this from an external file, you will need Ajax or a similar type of call. To use Ajax, you'll have to add a library called jQuery to your project's HTML file. Then you can call your JSON without referencing it as a javascript variable as you see in the following working code snippet.

/* I put your JSON into an external file, loaded from github */
var url = "https://raw.githubusercontent.com/mspanish/playground/master/jessica.json";

/* this tells the page to wait until jQuery has loaded, so you can use the Ajax call */

$(document).ready(function(){
  $.ajax({
    url: url,
    dataType: 'json',
      error: function(){
        console.log('JSON FAILED for data');
      },
    success:function(results){
  /* the results is your json, you can reference the elements directly by using it here, without creating any additional variables */
  
      var cartItemsList = document.getElementById("cartItemsList");

      results.basket.productList.forEach(function(element) {
      cartItemsList.insertAdjacentHTML( 'beforeend',"<li>" +              element.product.name + " : " + element.price+ " </li>");
      }); // end of forEach
    }  // end of success fn
   }) // end of Ajax call
 }) // end of $(document).ready() function
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

<h1>My Cart</h1>
<div id="cart">
    <h2>Cart Items</h2>
    <ul id="cartItemsList">
    </ul>
</div>

Sign up to request clarification or add additional context in comments.

1 Comment

@Jessica is this what you were looking for?
2

if you want to parse an object:

function logTheObj(obj) {
    var ret = "";
    for (var o in obj) {
        var data = obj[o];
        if (typeof data !== 'object') {
            ret += "<li>" + o + " : " + data + "</li>";
        } else {
            ret += "<li>" + o + " : " + logTheObj(data) + "</li>";
        }
    }
    return "<ul>" + ret + "</ul>";
}

If your object is in a string:

logTheObj(JSON.parse(jsonString));

Comments

1

Unless you use an Ajax call or something similar to load external JSON, you need to convert the JSON you've provided into an object that you can reference as a variable. Also, your JSON is not valid. I tried correcting it here, and am going to reference your JSON as an object you can reference via a variable named obj. Here is a working code snippet.

var obj = { 
"basket": {
		"productList": [{
			"product": {
				"id": "111",
				"name": "Dog",
				"shortDescription": "<p>Mans best friend</p>",
				"category": "Canine",
				"availability": "In Stock",
				"variationType": {
					"name": "Breed",
					"value": "Collie"
				}
			},
			"quantity": 1,
			"price": "$53.00"
		}, {
			"product": {
				"id": "112",
				"name": "Dog",
				"shortDescription": "<p>Not so best friend</p>",
				"category": "feline",
				"availability": "Low In Stock",
				"variationType": {
					"name": "breed",
					"value": "Maine Coon"
				}
			},
			"quantity": 1,
			"price": "$49.00"
		}, {
			"product": {
				"id": "113",
				"name": "Rabbit",
				"shortDescription": "Likes carrots",
				"category": "cuniculus",
				"availability": "In Stock"
			},
			"quantity": 1,
			"price": "$66.00"
		}]
	}
}

var cartItemsList = document.getElementById("cartItemsList");

obj.basket.productList.forEach(function(element) {
        cartItemsList.insertAdjacentHTML( 'beforeend',"<li>" + element.product.name + " : " + element.price+ " </li>");
});
 <h1>My Cart</h1>
    <div id="cart">
        <h2>Cart Items</h2>
        <ul id="cartItemsList">
        </ul>
    </div>

7 Comments

The same comment as on Elad's answer: Where does cartItemsList variable come from? You are also overwriting the innerHTML every iteration instead of adding a new list element every iteration.
cartItemsList is the element id where the list needs to be created, taken from the HTML snippet posted by Jessica - var products = document.getElementById("cartItemsList"); You can append to the HTML instead of rewriting, sure. I think Elad was trying to make it the easiest possible, as she mentioned that she needed things simple.
Yes, it probably is meant to refer to that element. But why isn't cartItemsList defined anywhere? There is even another variable called products that refers to the same element. Why is the same element defined twice in the same piece of code to a different variable? Easy code is good, but it should still behave as expected (add all list items to the list). I'm afraid this answer might end up adding more confusion for Jessica, because it only prints the last element to the list.
RMo is right, honestly this have left me more confused
I was focused on fixing her bad JSON, and showing how you reference JSON as variable. I see your point about Elad's code, products is not the right name for that var. So it should be var cartItemsList = document.getElementById("cartItemsList"); @Jessica you need to be more specific about what you are trying to achieve, and try reading up on objects in Javascript if you want to understand how to create and use them.
|
1

JavaScript version using external json file from previous answer by Stacey Reiman

const products = document.getElementById("cartItemsList");

/* get basket items from JSON */
class Basket {
    async cartItems() {
        try {
            let result = await fetch('https://raw.githubusercontent.com/mspanish/playground/master/jessica.json')
            let data = await result.json()
           // return data
            
           /* destructuring data */ 
         let basketItems = data.basket.productList
            basketItems = basketItems.map(item =>{
            const price = item.price
            const{id,name,shortDescription,category,availability} = item.product
            const breed = item.product.variationType
            const quantity = item.quantity
              
            return {price,id,name,shortDescription,category,availability,quantity,breed}
            })
            return basketItems 
            
        } catch (error) {
            console.log(error)  
        }
    }
}
/* Display stuff from the basket */
class Display {
    displayBasket(basket) {
    //console.log(basket)
         let result = ""
        basket.forEach((item)=>{
        result += `
        <li>
        id : ${item.id}
        name: ${item.name}
        price: ${item.price}
        availability: ${item.availability}
        category : ${item.category}
        quantity : ${item.quantity}
        shortDescription : ${item.shortDescription}
        </li>
        `})
        cartItemsList.innerHTML = result 
    }
}

document.addEventListener("DOMContentLoaded", ()=>{
    const basket  = new Basket()
    const display = new Display()

    basket.cartItems().then(basket => display.displayBasket(basket))
})
 <h1>My Cart</h1>
    <div id="cart">
        <h2>Cart Items</h2>
        <ul id="cartItemsList">
        </ul>
    </div>

Comments

0

First, you have to convert the json from long string to acutely js object. you doing so by the JSON.parse command. like so:

let jsObj = JSON.parse( youreJsonString);

Them, you can loop throw youre products in your productList and build your html code, like so:

var products = document.getElementById("cartItemsList");

jsObj.basket.productList.forEach( function(product ) {
        cartItemsList.innerHTML = "<li>" + product.name + " : " + product.price+ " </li>";
});

4 Comments

Sorry I don't understand. Is there another way you could explain? I don't understand how I am referencing the json object ... let jsObj = JSON.parse( youreJsonString); Also I don't understand what is "longstring"
Or could you point me in the right direction of what I need to learn in order to understand this?
Where does cartItemsList variable come from? You are also overwriting the innerHTML every iteration instead of adding a new list element every iteration.
@RMo From the the code in the question. Read the question properly before you dawn vote other people answers.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.