te')); return $arr; } /* 遍历用户所有主题 * @param $uid 用户ID * @param int $page 页数 * @param int $pagesize 每页记录条数 * @param bool $desc 排序方式 TRUE降序 FALSE升序 * @param string $key 返回的数组用那一列的值作为 key * @param array $col 查询哪些列 */ function thread_tid_find_by_uid($uid, $page = 1, $pagesize = 1000, $desc = TRUE, $key = 'tid', $col = array()) { if (empty($uid)) return array(); $orderby = TRUE == $desc ? -1 : 1; $arr = thread_tid__find($cond = array('uid' => $uid), array('tid' => $orderby), $page, $pagesize, $key, $col); return $arr; } // 遍历栏目下tid 支持数组 $fid = array(1,2,3) function thread_tid_find_by_fid($fid, $page = 1, $pagesize = 1000, $desc = TRUE) { if (empty($fid)) return array(); $orderby = TRUE == $desc ? -1 : 1; $arr = thread_tid__find($cond = array('fid' => $fid), array('tid' => $orderby), $page, $pagesize, 'tid', array('tid', 'verify_date')); return $arr; } function thread_tid_delete($tid) { if (empty($tid)) return FALSE; $r = thread_tid__delete(array('tid' => $tid)); return $r; } function thread_tid_count() { $n = thread_tid__count(); return $n; } // 统计用户主题数 大数量下严谨使用非主键统计 function thread_uid_count($uid) { $n = thread_tid__count(array('uid' => $uid)); return $n; } // 统计栏目主题数 大数量下严谨使用非主键统计 function thread_fid_count($fid) { $n = thread_tid__count(array('fid' => $fid)); return $n; } ?>How to parse nested JSON in Javascript? - Stack Overflow
最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

How to parse nested JSON in Javascript? - Stack Overflow

programmeradmin2浏览0评论

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 plete list of brands. Please advice. (I want to use plain javascript and not jquery)

Thanks!

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 plete list of brands. Please advice. (I want to use plain javascript and not jquery)

Thanks!

Share Improve this question edited Jun 15, 2016 at 19:58 Rohit asked Jun 15, 2016 at 19:52 RohitRohit 7,16119 gold badges61 silver badges109 bronze badges 2
  • what exactly you want to get from the JSON? – user3378165 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. – Rohit Commented Jun 15, 2016 at 19:57
Add a ment  | 

5 Answers 5

Reset to default 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.

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

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

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>

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"];
发布评论

评论列表(0)

  1. 暂无评论