-2

我似乎找不到这段代码有什么问题。我不断收到 Uncaught SyntaxError: Unexpected string in Chrome 控制台。

var json = '{"shipment":{"weight":"'+a[0].value+'","value":"0","quantity":"'+a[1].value+'","insurance":"false","dimensions":{"length":"30","width":"2","height":"10"},"origin":{"country":"'+a[2].value+'","formattedAddress":"'+a[3].value+'","locality":"'+a[4].value+'","postalCode":"'+a[5].value+'","contact":"'+a[6].value+'","email":"'+a[7].value+'","comments":"'+a[8].value+'"},"destination":{"country":"'+a[9].value+'","formattedAddress":"'+a[10].value+'","locality":"'+a[11].value'","postalCode":"'+a[12].value+'","contact":"'+a[13].value+'","email":"'+a[14].value+'","comments":"'+a[15].value+'"},"vehicleType":"'+a[16].value+'"}}';
4

1 回答 1

3

请为自己省去一千个头痛,而是这样做:

var data = {
  shipment: {
    weight:      a[0].value,
    value:       0,
    quantity:    a[1].value,
    insurance:   "false",
    dimensions:  { length: "30", width: "2", height: "10" },
    origin: {
      country:          a[2].value,
      formattedAddress: a[3].value,
      locality:         a[4].value,
      postalCode:       a[5].value,
      contact:          a[6].value,
      email:            a[7].value,
      comments:         a[8].value
    },
    destination: {
      country:          a[9].value,
      formattedAddress: a[10].value,
      locality:         a[11].value,
      postalCode:       a[12].value,
      contact:          a[13].value,
      email:            a[14].value,
      comments:         a[15].value
    },
    vehicleType: a[16].value
  }
};

var json = JSON.stringify(data);

或者,如果您希望您的代码在以后有点可维护性:

function addressDataFromArray(arr) {
  return {
    country:          a[0].value,
    formattedAddress: a[1].value,
    locality:         a[2].value,
    postalCode:       a[3].value,
    contact:          a[4].value,
    email:            a[5].value,
    comments:         a[6].value
  }
}

function shipmentDataFromArray(arr) {
  var originData      = addressDataFromArray( arr.slice(2, 8) ),
      destinationData = addressDataFromArray( arr.slice(9, 15) );

  return {
    weight:      arr[0].value,
    value:       0,
    quantity:    arr[1].value,
    insurance:   "false",
    dimensions:  { length: "30", width: "2", height: "10" },
    origin:      originData,
    destination: destinationData,
    vehicleType: arr[16].value
  }
}

var shipmentData = shipmentDataFromArray(a),
    json = JSON.stringify({ shipment: shipmentData });
于 2014-05-19T16:23:21.910 回答