3

I am trying to parse and show JSON data (product catalog) using XMLHttpRequest method. I am able to display the brands and their names, but not able to showcase list of products progmatically.

Here is the sample JSON request:

   {
    "products": {
        "laptop": [{
            "brand": "sony",
            "price": "$1000"
        }, {
            "brand": "acer",
            "price": "$400"
        }],
        "cellphone": [{
            "brand": "iphone",
            "price": "$800"
        }, {
            "brand": "htc",
            "price": "$500"
        }],
        "tablets": [{
            "brand": "iPad",
            "price": "$800"
        }, {
            "brand": "htc-tab",
            "price": "$500"
        }]
    }
}

Right now I am using following code to show data in tabluar form:

 function loadJSON() {

        var data_file = "http://localhost/AJAX/productcatalog.json";

        var http_request = new XMLHttpRequest();

        http_request.onreadystatechange = function () {

            if ((http_request.readyState == 4) && (http_request.status == 200)) {

                // Javascript function JSON.parse to parse JSON data
                var jsonObj = JSON.parse(http_request.responseText);
                data = '<table border="2"><tr><td>Type</td><td>Brand</td><td>Price</td></tr>';
                var i = 0;
                debugger;
                for (i = 0; i < jsonObj["products"].laptop.length; i++)
                {

                    obj = jsonObj["products"].laptop[i];

                    data = data + '<tr><td>laptop</td><td>' + obj.brand + '</td><td>' + obj.price + '</td></tr>';
                }
                for (i = 0; i < jsonObj["products"].cellphone.length; i++)
                {

                    obj = jsonObj["products"].cellphone[i];

                    data = data + '<tr><td>laptop</td><td>' + obj.brand + '</td><td>' + obj.price + '</td></tr>';
                }

                for (i = 0; i < jsonObj["products"].tablets.length; i++)
                {

                    obj = jsonObj["products"].tablets[i];

                    data = data + '<tr><td>laptop</td><td>' + obj.brand + '</td><td>' + obj.price + '</td></tr>';
                }

                data += '</table>';

                document.getElementById("demo").innerHTML = data;


            }
        }

        http_request.open("GET", data_file, true);
        http_request.send();
    }

Question What is the way to fetch product list , i.e. products, cellphone and tablets ? Right now I have hardcoded that in order to fetch complete list of brands. Please advice. (I want to use plain javascript and not jquery)

Thanks!

2
  • what exactly you want to get from the JSON? Commented Jun 15, 2016 at 19:55
  • I want to first get list of products, i.e. in this case they are products, cellphone and tablets. However I am not sure how to get that. Commented Jun 15, 2016 at 19:57

5 Answers 5

4

It sounds like what you're missing is the "How do I iterate over an object when I don't know all the keys".

An object is a set of key, value pairs. You can use for/in syntax: for( var <key> in <object> ){} to get each key.

For your use case it might be something like:

var products = jsonObject['products'];
for( var productName in products ){
  //productName would be "laptop", "cellphone", etc.
  //products[productName] would be an array of brand/price objects
  var product = products[productName];
  for( var i=0; i<product.length; i++ ){
    //product[i].brand
    //product[i].price
  }
}

In practice, I might use something a little less verbose, but this makes it easier to understand what is going on.

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

5 Comments

Here for( var i=0; i<product.length; i++ ) // product.length returns 8 for computer, however it should have returned the number of product it has...
product.length would be the number of brand/price objects under the "computer" product. Each element product[i], would be an item in the product catalog under the heading Computer.
Hi Chris, product.length is returning 8, i.e. length of computer. Please verify once.
Your sample JSON data doesn't contain the "computer" product, so I cannot confirm that there are actually 8 elements, but if you look at your raw JSON, you should be seeing an array of 8 items under the computer heading.
sorry i meant to say laptop, product = laptop, product.length=6
2

To achieve the expected i have used for loop and HTML DOM createElement() Method

          var product_catalog = {
        "products": {
          "laptop": [{
            "brand": "sony",
            "price": "$1000"
          }, {
            "brand": "acer",
            "price": "$400"
          }],
          "cellphone": [{
            "brand": "iphone",
            "price": "$800"
          }, {
            "brand": "htc",
            "price": "$500"
          }],
          "tablets": [{
            "brand": "iPad",
            "price": "$800"
          }, {
            "brand": "htc-tab",
            "price": "$500"
          }]
        }
      };

      var output = document.querySelector('#product tbody');

               function build(JSONObject) {
        /**get all keys***/
        var keys = Object.keys(JSONObject);
        /**get all subkeys***/ 
        var subkeys = Object.keys(JSONObject[keys]);
        console.log(subkeys);
        /**loop sub keys to build HTML***/
        for (var i = 0, tr, td; i < subkeys.length; i++) {
          tr = document.createElement('tr');
          td = document.createElement('td');
          td.appendChild(document.createTextNode(subkeys[i]));
          tr.appendChild(td);
          output.appendChild(tr);
        }
      };

      build(product_catalog);

HTML:

Coepen URL for reference- http://codepen.io/nagasai/pen/xOOqMv

Hope this works for you :)

3 Comments

what is x here? can you please provide some explaination
x is the parameter ....which i have used to define function and while calling function , i have passed the product catalog as the parameter and found keys and subkeys.....if you have another JSON with similar structure , you can use the same function and pass that JSON object as the parameter.
To make to it clear , i have updated x with "JSONObject" and updated codepen - codepen.io/nagasai/pen/xOOqMv Hope it works for you :)
1

Look at this example:

var x = data.key1.children.key4;

var path = "data";
function search(path, obj, target) {
    for (var k in obj) {
        if (obj.hasOwnProperty(k))
            if (obj[k] === target)
                return path + "['" + k + "']"
            else if (typeof obj[k] === "object") {
                var result = search(path + "['" + k + "']", obj[k], target);
                if (result)
                    return result;
            }
    }
    return false;
}

//Then for evry node that you need you can call the search() function.
var path = search(path, data, x);
console.log(path); //data['key1']['children']['key4']

1 Comment

Thanks, would be great, if you can please provide a brief explanation of this code.
1

I think this is what you're asking about, you can use Object.keys to get the properties of an object, then loop through them afterward.

var data = {
  "products": {
    "laptop": [{
      "brand": "sony",
      "price": "$1000"
    }, {
      "brand": "acer",
      "price": "$400"
    }],
    "cellphone": [{
      "brand": "iphone",
      "price": "$800"
    }, {
      "brand": "htc",
      "price": "$500"
    }],
    "tablets": [{
      "brand": "iPad",
      "price": "$800"
    }, {
      "brand": "htc-tab",
      "price": "$500"
    }]
  }
}

var typesOfProducts = Object.keys(data.products)

console.log(typesOfProducts)

document.getElementById('output').textContent = typesOfProducts.toString()

//Then, to loop through
var i = -1,
  len = typesOfProducts.length

function handleProduct(productType) {
  console.log("This is the " + productType + " data.")
  console.log(data.products[productType])
}

while (++i < len) {
  handleProduct(typesOfProducts[i])
}
<div id="output"></div>

Comments

1

It sounds like what you're looking for is just an array of the keys of the "products" object. Example:

Products: ["laptop", "cellphone", "tablets"];

If so, I would just run your json object through javascript's Object.keys() method.

var jsonObj = JSON.parse(http_request.responseText);
var products = Object.keys(jsonObj.products);
// products = ["laptop", "cellphone", "tablets"];

2 Comments

var products = Object.keys(jsonObj); it returns ["products"], however i need the list of products so that i can display them dynamically instead of hardcoding.
Try getting through that first layer of the jsonobj by using dot notation to bring up the object containing the products (i edited my answer to reflect that approach).

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.