Home > OS >  merge json under another json objects
merge json under another json objects

Time:07-14

there is a json like that :

json1 = `
{
  "webAPIModification": "`  new Date()   `",
  "AppSetting": {
    "setting-toastSound": true,
    "setting-animMode": true,
    "setting-landscape": "NAN"
  },
  "UserInfo": {
    "OS": "NAN"
  }
}`;

now i have another json like this:

json2 = `
{
  "ver": 1,
  "send": true,
  "status": "NAN"
}`;

how can add json2 into the json1 (under UserInfo) ?

json1 = `
{
  "webAPIModification": "`  new Date()   `",
  "AppSetting": {
    "setting-toastSound": true,
    "setting-animMode": true,
    "setting-landscape": "NAN"
  },
  "UserInfo": {
    "OS": "NAN",

    "ver": 1, <--> what i need
    "send": true, <--> what i need
    "status": "NAN" <--> what i need

  }
}`;

how i can do that in jquery or javascript way???

CodePudding user response:

You can make use of spread operator and add contents on json2 into json1.

const json3 ={
  ...json1,
  UserInfo:{
    ...json1.UserInfo,
    ...json2
  }
}

CodePudding user response:

Parse it into a standard JS object, combine the UserInfo object and finally stringify it back to JSON:

a = JSON.parse(json1);
b = JSON.parse(json2);
Object.assign(a.UserInfo, b);
json1 = JSON.stringify(a)

CodePudding user response:

A low level solution could be: use JSON.parse(jsonstring) in order to have objects and treat them as objects with properties or arrays and then you can set what you wan... after that you can get the json string with JSON.stringify(object).

let obj = JSON.parse(json1);
let otherUserInfo = JSON.parse(json2);

for (var index in otherUserInfo){
     obj.UserInfo[index] = otherUserInfo[index];
}

json1 = JSON.stringify(obj);
  • Related