在JSON文件访问数据(Accessing Data in the Json File)

2019-10-29 14:47发布

我有很难访问特定的JSON数据。 Here`s我的JSON文件

{
  "id": "72",
  "title": "Item Category Product Level Average Price Comparison",
  "xLabel": null,
  "yLabel": "Average Price",
  "zLabel": null,
  "data": [{
      "avgPrice": "87",

      "numProducts": "85"
    }, {
      "avgPrice": "60",

      "numProducts": "49"
    }, {
      "avgPrice": "59",

      "numProducts": "65"
    }

我想借此avgPrice和第一对应的商户名称的唯一值的numProducts的价值。 例如在JSON数据,第一和最后MERCHANTNAME是相同(即“MERCHANTNAME”:“A”)。 所以我想利用销售商A的价值首先和商人B(如果重复我想完成的是第一,然后去另一个商家吧。

var mn = [];
$.each(returnedData.data, function (index, value) {
  if($.inArray(value.merchantName, mn) == -1) {
    mn.push(value.merchantName);
  }
});
 //all the merchants name stored in mn[]

function get_items_by_merchant(merchant_name) {
  var items = new Array();
  $.each(returnedData.data, function (index, item) {
    if(returnedData.merchantName == merchant_name)
      items.push(item);
  });
  return items;
}
var CB_items = [];
for(var i = 0; i < mn.length; i++) {
  CB_items[i] = get_items_by_merchant(mn[i]);
  $.each(CB_items, function (index, item) {
    var avgpricve = parseFloat(response.data[i].avgPrice);
    var numproducts = parseFloat(response.data[i].numProducts);
    datajson = {
      x: avgpricve,
      y: numproducts
    }
    result_data.push(datajson)
  });
}

响应是JSON文件中的数据,我使用$ .getJSON得到它。 在上面的代码中,我想

访问商家名称线response.data [I] .MN [I] .avgPrice ..因为,我无法..有什么办法,我能做什么?

Answer 1:

在功能get_items_by_merchant改变这种

$.each(returnedData.data, function(index, item) {
                if (returnedData.merchantName == merchant_name) // There is not merchantName in returnedData.
                    items.push(item);
   });

 $.each(returnedData.data, function(index, item) {
            if (item.merchantName == merchant_name)
                items.push(item);
        });

最终代码的变化: -

演示

var result_data = [];
var mn = [];
$.each(returnedData.data, function (index, value) {
    if ($.inArray(value.merchantName, mn) == -1) {
        mn.push(value.merchantName);
    }
});
//all the merchants name stored in mn[]

function get_items_by_merchant(merchant_name) {
    var items = new Array();
    $.each(returnedData.data, function (index, item) {
        if (item.merchantName == merchant_name) items.push(item);
    });
    return items;
}
var CB_items = [];
for (var i = 0; i < mn.length; i++) {

    CB_items[i] = get_items_by_merchant(mn[i]);
    $.each(CB_items[i], function (index, item) {
        var avgpricve = parseFloat(item.avgPrice);
        var numproducts = parseFloat(item.numProducts);
        datajson = {
            x: avgpricve,
            y: numproducts
        }
        result_data.push(datajson)
    });
    console.log(result_data)


文章来源: Accessing Data in the Json File