我怎样才能在javascript中构建这个json?

时间:2014-01-07 08:51:28

标签: javascript json

我必须构建以下类型的json,

{
  "MyRquest": {
    "-xmlns:xsi": "http://www.w3.org/2001/XMLSchema-instance",
    "serialNo": "70813BACH194294",
    "orderslist": {
      "orderid": [
        "5026538",
        "5026539"
      ],
      "ordersource": [
        "ONLINE",
        "STORE"
      ],
      "transactiondtm": [
        "2013-10-08",
        "2013-10-09"
      ]
    }
  }
}

Orderid 5026538在线有订购源,其交易日期为2013-10-08。同样,我可能有5个订单及其相应的订单来源和交易时间。

如何在javascript中动态创建此json?

1 个答案:

答案 0 :(得分:2)

首先,创建对象:

var req = {
  "MyRquest": {
    "-xmlns:xsi": "http://www.w3.org/2001/XMLSchema-instance",
    "serialNo": "70813BACH194294",
    "orderslist": {
      "orderid":        [],
      "ordersource":    [],
      "transactiondtm": []
    }
  }
};

(真的MyRquest?)

然后根据需要添加;并行数组是一个脆弱的结构,可能最好有一个函数来执行它:

function addOrder(req, orderId, orderSource, transactiondtm) {
    req.MyRquest.orderslist.orderid.push(orderId);
    req.MyRquest.orderslist.ordersource.push(orderSource);
    req.MyRquest.orderslist.transactiondtm.push(transactiondtm);
}

然后,如果你真的想要JSON,你可以序列化它:

var str = JSON.stringify(req);