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

时间:2014-01-15 12:50:31

标签: javascript json

我有这个json,其值将在javascript中动态传递,

{
  "User": {
    "-xmlns:xsi": "http://www.w3.org/2001/XMLSchema-instance",
    "memNum": "70000211981",
    "orderslist": [
      {
        "orderid": "5119534",
        "ordersource": "ONLINE",
        "transactiondttm": "2014-01-09"
      },
      {
        "orderid": "5119534",
        "ordersource": "STORE",
        "transactiondttm": "2014-01-09"
      }
    ]
  }
}

我尝试使用此函数来构建json,但它似乎无法正常工作,

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

任何建议..

3 个答案:

答案 0 :(得分:1)

这样的事情应该有效。

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

答案 1 :(得分:1)

orderslist的元素是对象,而不是数组,所以你不能push到它们上面。您必须将它们构建为对象,然后将其推送到orderslist数组。

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

答案 2 :(得分:0)

可以像数组一样访问Javascript对象。 这样你就可以创建动态成员。

user = {"orderList":[]};

for(var i = 0; i<5; i++){
    user.orderList[i] = {};
    user.orderList[i]["orderId"] = i;
    user.orderList[i]["orderSource"] = "STORE";
}

alert(user.orderList[0].orderSource);
//Shows "STORE"

您可以在此处查看代码http://jsfiddle.net/wmgE6/

相关问题