使用API​​调用的相同键创建JSON对象

时间:2017-07-20 15:50:33

标签: javascript json api object

我正在尝试为API调用创建一个JSON对象,其格式如下:

  ....
  "Key": "Value",
  "Package": {
    "Dimensions": {
      "UnitOfMeasurement": {
        "Code": "IN",
        "Description": "inches"
      },
      "Length": "20",
      "Width": "25",
      "Height": "30"
    },
    "PackageWeight": {
      "UnitOfMeasurement": {
        "Code": "Lbs",
        "Description": "pounds"
      },
      "Weight": "80"
    }
  },
  "Package": {
    "Dimensions": {
      "UnitOfMeasurement": {
        "Code": "IN",
        "Description": "inches"
      },
      "Length": "15",
      "Width": "24",
      "Height": "27"
    },
    "PackageWeight": {
      "UnitOfMeasurement": {
        "Code": "Lbs",
        "Description": "pounds"
      },
      "Weight": "50"
    }
  },
  "Key": "Value",
  ....

我应该添加尽可能多的" Package"对象根据需要。但是,我尝试过多种不同的方法,但是每次解析要使用的变量时,第一个对象都会被覆盖,最后只有最后一个对象。

这就是我现在正在尝试的,仍然没有运气:

var lineItems = '{';
  for (var i=0;i<inputObject.packages.length;i++) {
      lineItems += '"Package": {"PackagingType": {"Code": "02","Description": "Rate"},"Dimensions": {"UnitOfMeasurement": {"Code": "IN","Description": "inches"},"Length": ' + inputObject.packages[i][0].toString() + ',"Width": ' + inputObject.packages[i][1].toString() + ',"Height": ' + inputObject.packages[i][2].toString() + '},"PackageWeight": {"UnitOfMeasurement": {"Code": "Lbs","Description": "pounds"},"Weight": ' + inputObject.packages[i][3].toString() + '}}';
      if (i !== inputObject.packages.length-1) {
          lineItems += ',';
      }
  }

  lineItems += '}';

  lineItems = JSON.parse(lineItems);

1 个答案:

答案 0 :(得分:0)

如何为您的包编号,即:

             for (var i=0;i<inputObject.packages.length;i++) {
                   lineItems+='"Package" + i : { ... }'
                  }

编辑:获取所需的结果(作为数组 - 因为它不是JSON),这是一个例子:

var a=[];
var b={"package": {"c":100,"d":200,"e":300}}
var c={"package": {"c":800,"d":700,"e":600}}
a.push(b);
a.push(c);
console.log(a);