'Read two files which has json data and create new dictionary using 2 files data

My files have data as

file1.txt

Student={'name'='john','age'=13,'roll_no':22445,'gender'='male'},{'name'='jimmy','age'=14,'roll_no':45622,'gender'='male'}

file2.txt

Address1={'name':'john','roll_no'=22445,'street':'st johns','pin':56902,'country':'US'},{'name':'jimmy','roll_no'=45622,'street':'st peters','pin':56502,'country':'US'}

when i read the file and try loading it to json.i was getting list instead of dict

with open('file1.txt','r') as inputfile1:
        new_file=json.dumps(inputfile1)
        new_file=json.loads(new_file)

with open('file2.txt','r') as inputfile2:
        new_file2=json.dumps(inputfile2)
        new_file2=json.loads(new_file2)

print(type(new_file1))
print(type(new_file2))

New to python, can someone help



Solution 1:[1]

Ur data into files is invalid json string. Try make better it valid json before write data into files. If it impossible, here is example how to fix it:

import json
Student='''{'name'='john','age'=13,'roll_no':22445,'gender'='male'},{'name'='jimmy','age'=14,'roll_no':45622,'gender'='male'}'''
Address1='''{'name':'john','roll_no'=22445,'street':'st johns','pin':56902,'country':'US'},{'name':'jimmy','roll_no'=45622,'street':'st peters','pin':56502,'country':'US'}'''

#make valid json of ur string
Address1=Address1.replace("'",'"') #replace single quotes to double
Address1=Address1.replace('=',':') #
Address1='['+Address1+']'

a=json.loads(Address1)


Student=Student.replace("'",'"') #replace single quotes to double
Student=Student.replace('=',':') #
Student='['+Student+']'

s=json.loads(Student)

#type(a)
#<class 'list'>

a.extend(s)
print(a)
'''
[{'name': 'john', 'roll_no': 22445, 'street': 'st johns', 'pin': 56902, 'country
': 'US'}, {'name': 'jimmy', 'roll_no': 45622, 'street': 'st peters', 'pin': 5650
2, 'country': 'US'}, {'name': 'john', 'age': 13, 'roll_no': 22445, 'gender': 'ma
le'}, {'name': 'jimmy', 'age': 14, 'roll_no': 45622, 'gender': 'male'}]
'''

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 ganz