How to parse nested JSON in Javascript?

梦想的初衷 提交于 2021-02-07 10:36:36

问题


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!


回答1:


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.




回答2:


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']



回答3:


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 :)




回答4:


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>



回答5:


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"];


来源:https://stackoverflow.com/questions/37844560/how-to-parse-nested-json-in-javascript

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!