簡體   English   中英

將數據添加到JSON數組

[英]Adding data to JSON array

我的Node.js代碼中有一個JSON數組,具有以下架構:

{
    "status": "ok",
    "data": [
        {
            "id": 1,
            "active": true,
            "createdAt": "2017-07-21T15:39:31.000Z",
            "updatedAt": "2017-07-21T15:47:13.000Z"
        }
     ]
 }

我想添加數據,使其看起來像:

{
    "status": "ok",
    "data": [
        {
            "id": 1,
            "active": true,
            "createdAt": "2017-07-21T15:39:31.000Z",
            "updatedAt": "2017-07-21T15:47:13.000Z",
            "information": "someInformation"
        }
     ]
 }

你能幫我怎么做嗎?

謝謝!

像這樣? 訪問obj變量的data屬性以及該數組中的第一個元素,然后在該對象上設置一個與您的字符串相等的新屬性。

 var obj = { "status": "ok", "data": [ { "id": 1, "active": true, "createdAt": "2017-07-21T15:39:31.000Z", "updatedAt": "2017-07-21T15:47:13.000Z" } ] }; obj.data[0].information = "someInformation"; console.log( obj ); 

由於您已經有了JSON,因此您應該首先對其進行解析,因為JSON是一個字符串。 解析后,您將獲得應保存在某個變量中的對象,然后可以將其作為常規對象進行訪問並添加所需的屬性。 然后,您必須再次將其轉換為JSON字符串。 就像這樣

 var parsed = JSON.parse(data); // Now we are transforming JSON string into the object //Now you may do whatever you want parsed.newprop = 'some text'; parsed.hello = 'Hellow world'; data = JSON.stringify(parsed); // Now we are replacing the previous version of JSON string to new version with additional properties 

var dataContainer = {
     "status": "ok",
     "data": [
      {
        "id": 1,
        "active": true,
        "createdAt": "2017-07-21T15:39:31.000Z",
        "updatedAt": "2017-07-21T15:47:13.000Z"
      }
   ]
};


for(var i = 0; i < dataContainer.data.length; i++) {
  dataContainer['data'][i]['information'] = "some information";
}

希望對您有幫助!

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM