Tengo un archivo .json con este formato:
{
"filename": "usersInfo",
"userType": "adminUser",
"Date": "02/20/2022",
"type": "countrySample",
"file_version": "1.0",
"userInfo": [
{
"country": "USA",
"State": "Texas"
},
{
"country": "Canada",
"State": "Alberta"
},
{
"country": "USA",
"State": "California"
},
{
"country": "Canada",
"State": "British Columbia"
},
{
"country": "Australia",
"State": "NSW"
}
]
}
Quiero juntar listas de estados del mismo país; esta es la respuesta que tengo que obtener:
{
"filename": "usersInfo",
"userType": "adminUser",
"Date": "02/20/2022",
"type": "countrySample",
"file_version": "1.0",
"userInfo": [
{
"country": "USA",
"State": [
"Texas",
"California"
]
},
{
"country": "canada",
"State": [
"Alberta",
"British Columbia"
]
},
{
"Country": "Australia",
"State": [
"NSW"
]
}
]
}
He intentado esto:
import json
file_name = 'file1.json'
def read_json_get_country(file_name):
countries = []
with open(file_name) as file:
data = json.load(file)
for row in data['userInfo']:
if row['country'] not in countries:
countries.append(row['country'])
return countries
def read_json(file_name, countries):
response = {}
response['State'] = []
op_dict = dict()
with open(file_name) as file:
data = json.load(file)
filename = data['filename']
userType = data['userType']
date = data['Date']
type_ = data['type']
file_version = data['file_version']
#response.append({ 'filename': filename, 'userType': userType, 'Date': date, 'type': type_, 'file_version': file_version})
for row in data['userInfo']:
for country in countries:
if country in row['country']:
#print(country, row['State'])
response['State'].append(row['State'])
print(response)
countries = read_json_get_country(file_name)
read_json(file_name, countries)