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}];
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 documents in json.net?
The JSON.NET documentation has an article just for that: Merging JSON. You can use JObject.Merge
to merge two different objects into one:
JObject o1 = JObject.Parse(@"{
'FirstName': 'John',
'LastName': 'Smith',
'Enabled': false,
'Roles': [ 'User' ]
}");
JObject o2 = JObject.Parse(@"{
'Enabled': true,
'Roles': [ 'User', 'Admin' ]
}");
o1.Merge(o2, new JsonMergeSettings
{
// union array values together to avoid duplicates
MergeArrayHandling = MergeArrayHandling.Union
});
What you posted is two objects. A JSON document may be text, but what it contains are arrays and objects. "Merging" means finding a way to combine those objects/arrays and produce a new array or object.Merge is defined by JContainer, the parent of both JObject and JArray. This means you can use Merge
to merge both arrays and objects.
Another option with arrays is to use Enumerable.Union
to combine the contents of both arrays, and create a new one :
var array1= JArray.Parse("[1,2,3]");
var array2= JArray.Parse("[3,4,5, \"a\"]");
var array3=new JArray(array1.Union(array2));
This returns [1,2,3,4,5,"a"]
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};
Combine two json sections into one json object
You can use Object.assign()
to concatenate your objects.
var newObj = Object.assign({}, topData, bottomData)
From MDN:
The
Object.assign()
method is used to copy the values of all
enumerable own properties from one or more source objects to a target
object. It will return the target object.
var topData = { "auth": "1vmPoG22V3qqf43mPeMc", "property" : "ATL-D406", "status" : 1, "user" : "test001@aaa.com", "name" : "Abraham Denson"}
var bottomData = { "agent" : "pusher@agent.com", "agency" : "Thai Tims Agency", "agentCommission" : 1000, "arrival" : "arrive 12pm at condo", "departure" : "leaving room at 6pm",}
var completeData = Object.assign({}, topData, bottomData);
console.log(completeData);
Merge two JSON Objects in MS SQL
Original answer:
A possible approach is using JSON_MODIFY()
and JSON_QUERY()
, but you need at least SQL Server 2016 to use the built-in JSON support. The idea is to extract the "Cricketer"
JSON array from the second JSON (using JSON_QUERY()
with the appropriate path) and append it to the first JSON (using JSON_MODIFY()
):
JSON:
DECLARE @json1 nvarchar(max) = N'{"Celebrity": [
{"Name": "SRK", "Surname": "Kajol"},
{"Name": "Ajay", "Surname": "Devgan"}
]}'
DECLARE @json2 nvarchar(max) = N'{"Cricketer": [
{"Name": "Virat", "Surname": "Kohli"},
{"Name": "Sachin", "Surname": "Tendulkar"}
]}'
Statement:SELECT @json1 = JSON_MODIFY(@json1, '$."Cricketer"', JSON_QUERY(@json2, '$."Cricketer"'))
SELECT @json1
Result:{"Celebrity": [
{"Name": "SRK", "Surname": "Kajol"},
{"Name": "Ajay", "Surname": "Devgan"}
],"Cricketer":[
{"Name": "Virat", "Surname": "Kohli"},
{"Name": "Sachin", "Surname": "Tendulkar"}
]}
Update:If you want to build a JSON output from different tables, the approach below is also an option:
SELECT
Celebrity = (SELECT Name, Surname FROM TableA FOR JSON AUTO),
Cricketers = (SELECT Name, Surname FROM TableB FOR JSON AUTO)
FOR JSON PATH, WITHOUT_ARRAY_WRAPPER
using Python Merge two json file with each file having multiple json objects
You can read line by line then parse
# asuming
# File1.json
# {"id": 1, "name": "Ault", "class": 8, "email": "ault@pynative.com"}
# {"id": 2, "name": "john", "class": 8, "email": "jhon@pynative.com"}
# {"id": 3, "name": "josh", "class": 8, "email": "josh@pynative.com"}
# {"id": 4, "name": "emma", "class": 8, "email": "emma@pynative.com"}
# File2.json
# {"id": 4, "math": "A", "class": 8, "physics": "D"}
# {"id": 2, "math": "B", "class": 8, "physics": "C"}
# {"id": 3, "math": "A", "class": 8, "physics": "A"}
# {"id": 1, "math": "C", "class": 8, "physics": "B"}
import json
merged = {}
with open('File1.json') as f:
for line in f:
jsonified = json.loads(line)
merged[jsonified['id']] = jsonified
with open('File2.json') as f:
for line in f:
jsonified = json.loads(line)
merged[jsonified['id']].update(jsonified) # asuming both file has same ids otherwise use try catch
merged = list(merged.values())
print(merged)
[{'id': 1,
'name': 'Ault',
'class': 8,
'email': 'ault@pynative.com',
'math': 'C',
'physics': 'B'},
{'id': 2,
'name': 'john',
'class': 8,
'email': 'jhon@pynative.com',
'math': 'B',
'physics': 'C'},
{'id': 3,
'name': 'josh',
'class': 8,
'email': 'josh@pynative.com',
'math': 'A',
'physics': 'A'},
{'id': 4,
'name': 'emma',
'class': 8,
'email': 'emma@pynative.com',
'math': 'A',
'physics': 'D'}]
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)
}
}, []);
Related Topics
How to Use Local Storage in Angular
How to Reset the Scale/Zoom of a Web App on an Orientation Change on the Iphone
How to Execute a Dynamically Loaded JavaScript Block
Why Does If("String") Evaluate "String" as True But If ("String"==True) Does Not
Load "Vanilla" JavaScript Libraries into Node.Js
Cannot Set Property 'Innerhtml' of Null
Angular Ui-Router $Urlrouterprovider .When Not Working When I Click <A Ui-Sref="...">
Gmail Extension, Sendmessage to Background from Page Context
Why Do Empty JavaScript Arrays Evaluate to True in Conditional Structures
Passing a PHP Variable to JavaScript in a Blade Template
Differencebetween Settimeout(Fn, 0) and Settimeout(Fn, 1)
JavaScript Curry: What Are the Practical Applications
Execute an Exe File Using Node.Js
What Is #Auto Attribute Here and Why It Is Required
With JavaScript, How to Change the Z Index/Layer of an Svg <G> Element
Rendering to Js with Jinja Produces Invalid Number Rather Than String