2

I have couple of json String which I got using JSON.stringify and now have to combine all jsonString in one single json.

below are the 3 json strings I have

json 1= '{
   "authSeqNo" : 14,
  "flagNewEdit": "EDIT",
  "groupId": "AD0009",
  "groupName": "IT-Updated",
  "roleId": "Admin-Updated",
  "recordStatus": "A"
}'
json 2=
 {"userList": [
    {
      "userId": "x",
      "email": "x@gamail.com",
      "isDelete" : "TRUE"
    },
    {
      "userId": "y",
      "email": "y@gmail.com",
      "isDelete" : "FALSE"
    }
  ]}
json 3=
{"authMenuList": [
    {
    "menuId" : "ATHMGT",
    "viewFlag": "1",
    "createFlag": "1",
    "editFlag": "0",
    "deleteFlag": "1",
    "creditnoteFlag": "0",
    "cancelFlag": "1"
  }]}

Now have to join all these 3 to 1, I have tried the below way

var completeDetails = json1.concat(json2);
completeDetails=completeDetails.concat(json3);

but it's not giving the desired output.

my expected result should be like below

 {
   "authSeqNo" : 14,
  "flagNewEdit": "EDIT",
  "groupId": "AD0009",
  "groupName": "IT-Updated",
  "roleId": "Admin-Updated",
  "recordStatus": "A",

  "userList": [
    {
      "userId": "x",
      "email": "x@gmail.com",
      "isDelete" : "TRUE"
    },
    {
      "userId": "y",
      "email": "y@gmail.com",
      "isDelete" : "FALSE"
    }
  ],
  "authMenuList": [
    {
    "menuId" : "ATHMGT",
    "viewFlag": "1",
    "createFlag": "1",
    "editFlag": "0",
    "deleteFlag": "1",
    "creditnoteFlag": "0",
    "cancelFlag": "1"
  }]
}

but I getting output is

{
    "authSeqNo": "0",
    "flagNewEdit": "NEW",
    "groupId": "TEST",
    "groupName": "GroupN",
    "roleId": "Administrator",
    "recordStatus": ""
} {
    "userList": "[{"
    userId ":"
    x ","
    email ":"
    x @v.com ","
    delete ":"
    "},  {
        "userId": "asdkl",
        "email": "x@sd.com",
        "delete": ""
    }]
"}  {
    "authMenuList[{"
    menuId ":"
    ATHMGT ","
    viewFlag ":"
    1 ","
    createFlag ":"
    1 ","
    editFlag ":"
    0 ","
    deleteFlag ":"
    1 ","
    creditnoteFlag ":"
    0 ","
    cancelFlag ":"
    1 "}]}

I am new to javascript and learning it. Please help me to solve this.

melpomene
  • 84,125
  • 8
  • 85
  • 148
vicky9988
  • 66
  • 2
  • 3
  • 14
  • You're _in JavaScript_, so the obvious question would be "why are you working with JSON strings?". Turn the JSON into real JS using JSON.parse, then do all the work you need to do with those objects, and then use JSON.stringify() with the result once you're done? – Mike 'Pomax' Kamermans Aug 20 '19 at 22:50
  • Please check https://stackoverflow.com/questions/21450060/how-to-join-two-javascript-objects-without-using-jquery – Jaydp Aug 20 '19 at 23:20
  • [JSON](http://json.org) is a text representation of some data structure (usually an object or an array but simpler types can also be encoded as JSON). Concatenating two JSONs does not produce a JSON. The answer to your question is simple: do not encode the data structures as JSON (or decode the JSONs back into data structures if you didn't generate but received them from outside), join the data structures then encode the result of the join as JSON. – axiac Aug 20 '19 at 23:23
  • The second and third "JSON"s in your examples are not JSONs at all. They are JavaScript objects. JSONs are strings. – axiac Aug 20 '19 at 23:25

3 Answers3

6

You could convert them to JS objects and combine them

So:

const obj1 = JSON.parse(json1);
const obj2 = JSON.parse(json2);
const obj3 = JSON.parse(json3);

const mergedObj = Object.assign(obj1, obj2, obj3);

const jsonStr = JSON.stringify(mergedObj);

jsonStr should have the three JSONs combined


I just saw that you use JSON.stringify() to get your strings, so if you have three objects, just do the Object.assign() portion and you should be good.

Max
  • 469
  • 4
  • 7
  • I tried this but getting error `Object doesn't support property or method 'assign'` as I guess,IE not support this method,related to this I found one answer ~https://stackoverflow.com/a/39021339/2688406 but it doesn't fit in my situation as I am not using polyfill,its simple web applicaiton and not using any framework.is there any other way or the way to fix this – vicky9988 Aug 20 '19 at 23:45
  • A polyfill is simply adding the equivalent method to the prototype, I'm sure you can find the Object.assign polyfill in MDN and simply place the code before the rest of your app and it should be available. – Max Aug 21 '19 at 00:01
0

If you would want to use jQuery, you can use $.extend function to merge all your parsed json strings into one single javascript object and stringify the result. Code sample below.

    const object1 = JSON.parse(json_1);
    const object2 = JSON.parse(json_2);
    const object3 = JSON.parse(json_3);

    const mergedObject = $.extend({}, object1, object2, object3);

    const mergedJSON = JSON.stringify(mergedObject);

    console.log(mergedJSON);

By passing an empty object as the target(first) argument, you can preserve both the objects. If however you want to merge the second and third object, you can do like $.extend(object2, object3).

See documentation here - jQuery.extend API

Junius
  • 589
  • 2
  • 12
  • 41
0

const json1= `{
   "authSeqNo" : 14,
  "flagNewEdit": "EDIT",
  "groupId": "AD0009",
  "groupName": "IT-Updated",
  "roleId": "Admin-Updated",
  "recordStatus": "A"
}`
const json2=`
 {"userList": [
    {
      "userId": "x",
      "email": "x@gamail.com",
      "isDelete" : "TRUE"
    },
    {
      "userId": "y",
      "email": "y@gmail.com",
      "isDelete" : "FALSE"
    }
  ]}`
const json3=`
{"authMenuList": [
    {
    "menuId" : "ATHMGT",
    "viewFlag": "1",
    "createFlag": "1",
    "editFlag": "0",
    "deleteFlag": "1",
    "creditnoteFlag": "0",
    "cancelFlag": "1"
  }]}`
  
const extendJSON = (...objs) => objs.reduce((result, current) => ({...result, ...JSON.parse(current)}), {});
  
console.log(extendJSON(json1, json2, json3));
Adrian Brand
  • 20,384
  • 4
  • 39
  • 60
  • its giving the result which I am expecting as I can see here , but didnt get what is `result` and `current`,can you please help to understand the solution as you are not passing the any of the json object in the `const extendJSON = (...objs) => objs.reduce((result, current) => ({...result, ...JSON.parse(current)}), {}); ` expression – vicky9988 Aug 20 '19 at 23:50
  • 1
    Read up on how a reduce works, if you understand the reduce function you will understand the function I have written. result is the accumulator and current is the current iteration. https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/reduce – Adrian Brand Aug 21 '19 at 00:12
  • ... is the spread operator, it takes the properties of an object and adds them to a new object. https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Spread_syntax – Adrian Brand Aug 21 '19 at 00:22