'Combining json in Python
I have the below code
connection = psycopg2.connect(*******************)
cursor = connection.cursor()
sql = "SELECT schema_old FROM table_1 where ingestion_id=1;"
cursor.execute(sql)
result = cursor.fetchall()
schema_output='\n'.join(''.join(elems) for elems in result)
json_data=json.loads(schema_output)
print(json_data)
sql1 = "SELECT schema_new FROM table_1 where ingestion_id=1;"
cursor.execute(sql1)
result1 = cursor.fetchall()
schema_output1='\n'.join(''.join(elems) for elems in result1)
json_data1=json.loads(schema_output1)
where:
json_data= [{'name': 'status', 'type': 'STRING', 'mode': 'NULLABLE'}, {'name': 'address', 'type': 'STRING', 'mode': 'NULLABLE'}, {'name': 'city', 'type': 'STRING', 'mode': 'NULLABLE'}]
json_data1= [{'name': 'phone', 'type': 'STRING', 'mode': 'NULLABLE'}]
I want to combine the jsons: json_data + json_data1
, so that the final json is:
[{'name': 'status', 'type': 'STRING', 'mode': 'NULLABLE'}, {'name': 'address', 'type': 'STRING', 'mode': 'NULLABLE'}, {'name': 'city', 'type': 'STRING', 'mode': 'NULLABLE'}, {'name': 'phone', 'type': 'STRING', 'mode': 'NULLABLE'}]
I tried doing:
thejson1["data"].extend(thejson2["data"])
and
c = dict(a.items() + b.items())
But it did not work.
Solution 1:[1]
Solution:
Like @Klas mentioned just the below was enough:
mjson=json_data+json_data1
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
Solution | Source |
---|---|
Solution 1 | aslfkhsalfgals |