Merging Two Json by Adding Their Value

Concatenate two JSON objects

Based on your description in the comments, you'd simply do an array concat:

var jsonArray1 = [{'name': "doug", 'id':5}, {'name': "dofug", 'id':23}];
var jsonArray2 = [{'name': "goud", 'id':1}, {'name': "doaaug", 'id':52}];
jsonArray1 = jsonArray1.concat(jsonArray2);
// jsonArray1 = [{'name': "doug", 'id':5}, {'name': "dofug", 'id':23},
//{'name': "goud", 'id':1}, {'name': "doaaug", 'id':52}];

Merging two JSON files with common key values when there are other objects in the file

First construct a dictionary, and then use it to perform the update:

jq --argfile new 2.json '
($new | INDEX(.NAME)) as $dict
| .objects.ne_110m_admin_0_countries.geometries[].properties
|= (if $dict[.NAME] then . + $dict[.NAME] else . end)
' 1.json

Incidentally ...

The hardest part here was determining the relevant path. jq came to the rescue:

jq -c 'paths(. == "Afghanistan")' 1.json

Another possibility would have been to blindly update every value associated with "properties":

($new | INDEX(.NAME)) as $dict
| walk(if type == "object" and .properties
then .properties |= . + $dict[.NAME]
else . end)

This actually produces the same result.

Merge two json array into one

There are some missing pieces there, but I think I see what's happening.

Based on the result you're getting, it looks like $posts and $post_image in this code are eloquent models.

return $this->successResponse($posts.$post_image ); 

When you concatenate them, their __toString() methods convert them to strings, which is done using the toJson() method. So basically you have two JSON objects stuck together, which isn't valid JSON, and then the successResponse() method encodes them again.

To merge them, you can convert them to arrays, merge those, then pass the result to successResponse().

$merged = array_merge($posts->toArray(), $post_image->toArray());
return $this->successResponse($merged);

The result you want is impossible, though. The "post" object has two different values of "id". You'll only be able to get one. If you use

$merged = array_merge($posts->toArray(), $post_image->toArray());

Then the id value of the second object will replace the first one. If you want to keep the first id value, you need to use union instead of array_merge.

$merged = $a->toArray() + $b->toArray(); 

ReactJS : Immutable.js : merge two Json objects

You can do merge using javascript spread operator which is introduced in ES6 onwards.

var obj1 = {id: 1, first_name: "abc", surname: "def", children: ["kid1", "kid2"]}

var obj2 = {first_name: "abc", surname: "def", email: "abc.def@gmail.com", mobile: ""}

var mergedObj = {...obj1,...obj2};

Merge two json object in python

In json module, dumps convert python object to a string, and loads convert a string into python object. So in your original codes, you just try to concat two json-string. Try to code like this:

import json

from collections import defaultdict


def merge_dict(d1, d2):
dd = defaultdict(list)

for d in (d1, d2):
for key, value in d.items():
if isinstance(value, list):
dd[key].extend(value)
else:
dd[key].append(value)
return dict(dd)


if __name__ == '__main__':
json_str1 = json.dumps({"a": [1, 2]})
json_str2 = json.dumps({"a": [3, 4]})

dct1 = json.loads(json_str1)
dct2 = json.loads(json_str2)
combined_dct = merge_dict(dct1, dct2)

json_str3 = json.dumps(combined_dct)

# {"a": [1, 2, 3, 4]}
print(json_str3)

How to merge two json array which has same value in react native in a javascript

I would suggest instead of making a result an array like this:

 const result = [
{
subject_id: "711",
subjectName: "Science",
topics: [ "Test", "Test2" ]
},
{
subject_id: "712",
subjectName: "Maths",
topics: [ "topic1", "Topic2" ]
}
];

You make it an object mapped with the subject_id:

 const result = {
"711":{
subjectName: "Science",
topics: [ "Test", "Test2" ]
},
"712":{
subjectName: "Maths",
topics: [ "topic1", "Topic2" ]
}
];

And your useEffect would be cleaner if you use async/await like this:

 const [orderdetails, setOrderdetails] = useState([]);
const [ordertracking, setOrdertracking] = useState([]);

useEffect(async () => {
try{
var res1 = await fetch('first api')
var data1 = await res1.json()
var res2 = await fetch('second api')
var data2 = await res2.json()
setOrderdetails(data1)
setOrdertracking(data2)
var res = {}
for(let d1 of data1.content){
res[d1.subject_id] = {
topics:d1.topics
}

}
for(let d2 of data2.content){
if(res[d2.subject_id]){
res[d2.subject_id].subjectName = d2.subjectName
}


}
console.log(res)
}catch(e){
console.error(e)
}finally{
setLoading(false)
}
}, []);

If you want to keep result an array use this

 const [orderdetails, setOrderdetails] = useState([]);
const [ordertracking, setOrdertracking] = useState([]);

useEffect(async () => {
try{
var res1 = await fetch('first api')
var data1 = await res1.json()
var res2 = await fetch('second api')
var data2 = await res2.json()
setOrderdetails(data1)
setOrdertracking(data2)
var res = []
for(let d1 of data1.content){
res.push({...d1,...data2.content.find(d2=>d2.subject_id==d1.subject_id)})

}
console.log(res)
}catch(e){
console.error(e)
}finally{
setLoading(false)
}
}, []);

How to merge two json object values by id with plain Javascript (ES6)

You could use Map and Object.assign for merging the objects.

var request1 = [{    ObjId: 174864,    ObjMutationD: "2010-07-09T00:00:00.000Z",    ObjMitarbeiterS: "epf",    ObjAufId: 142  }, {    ObjId: 175999,    ObjMutationD: "2010-07-09T00:00:00.000Z",    ObjMitarbeiterS: "epf",    ObjAufId: 149  }],  request2 = [{    ObjId: 174864,    MulPfadS: "M:\\Originalbilder\\FGS\\95nn",    MulDateiS: "9576.305-034-1",    MulExtentS: "jpg"  }, {    ObjId: 177791,    MulPfadS: "M:\\Originalbilder\\FGS\\95nn",    MulDateiS: "9576.305-035-1",    MulExtentS: "jpg"  }];
var result = [...[request1, request2].reduce((m, a) => (a.forEach(o => m.has(o.ObjId) && Object.assign(m.get(o.ObjId), o) || m.set(o.ObjId, o)), m), new Map).values()];
console.log(result);
.as-console-wrapper { max-height: 100% !important; top: 0; }

How to combine JSON object with same key and add their other corresponding values?

You can use Array.prototype.reduce() to collect unique items in an dictionary, and then transform the dictionary back to array using Array.prototype.map():

function combine(arr) {  var combined = arr.reduce(function(result, item) {    var current = result[item.level];
result[item.level] = !current ? item : { level: item.level, price: current.price + item.price, quantity: current.quantity + item.quantity, seats: current.seats + ',' + item.seats };
return result; }, {});
return Object.keys(combined).map(function(key) { return combined[key]; });}
var SeatWithCat = [{"level":"Level II","price":5,"quantity":1,"seats":"B3"},{"level":"Level II","price":5,"quantity":1,"seats":"B1"},{"level":"Level I","price":10,"quantity":1,"seats":"A2"},{"level":"Level III","price":30,"quantity":1,"seats":"C1"},{"level":"Level III","price":30,"quantity":1,"seats":"C2"},{"level":"Level V","price":50,"quantity":1,"seats":"E1"},{"level":"Level II","price":5,"quantity":1,"seats":"B2"},{"level":"Level VI","price":2,"quantity":1,"seats":"F1"}];
var result = combine(SeatWithCat);
console.log(result);


Related Topics



Leave a reply



Submit