将json对象附加到现有的json对象数组

时间:2018-06-07 09:55:30

标签: java json

我试图在现有的json对象数组中追加新的json对象。我是json的新人。所以请帮助我。

现有的json:

{
   "cluster":[
      {
         "path":"home/Nik",
         "password":"welcome",
         "isQueen":"true",
         "host":"192.168.11.248",
         "isQueenWorker":"true",
         "user":"Nik"
      }
   ]
}

new json:

{
   "path":"home\/Nik",
   "password":"welcome",
   "isQueen":"true",
   "host":"192.168.11.248",
   "isQueenWorker":"true",
   "user":"Nik"
}

我想将新的json添加到现有的json数组中。

2 个答案:

答案 0 :(得分:1)

您可以像下面一样使用它,您需要使用push命令来推送数组中的对象。

var myObj = {
   "cluster":[
      {
         "path":"home/Nik",
         "password":"welcome",
         "isQueen":"true",
         "host":"192.168.11.248",
         "isQueenWorker":"true",
         "user":"Nik"
      }
   ]
};
var x = {
   "path":"home\/Nik",
   "password":"welcome",
   "isQueen":"true",
   "host":"192.168.11.248",
   "isQueenWorker":"true",
   "user":"Nik"
};
alert(JSON.stringify(myObj))
var newArr = myObj.cluster; 
newArr.push(x) //pushing object x in newArr. similarly you can add multiple objects in to it
var myJSON = JSON.stringify(newArr);
alert(myJSON)

答案 1 :(得分:0)

你可以直接追加

例如。第一个json

{"cluster":[{"path":"home/Nik","password":"welcome","isQueen":"true","host":"192.168.11.248","isQueenWorker":"true","user":"Nik"}]}

int i = cluster.length();

cluster[i]={"path":"home/Nik","password":"welcome","isQueen":"true","host":"192.168.11.248","isQueenWorker":"true","user":"Nik"}
相关问题