I have a .json file with this format:
{
"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"
}
]
}
I want to put together lists of states from the same country; This is the response I have to get:
{
"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"
]
}
]
}
I have tried this:
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)
You can do it in the following way:
I tried it and it gives me the expected result, it has something like this:
Obviously you can change the names of the variables for something more representative and that does not generate confusion.
In order to have everything with the same information, you must place it in the following way:
you have something like this:
(Let's see if that's how I earn the points)
The crux of your requirement is how to convert a certain format that has a list of dictionaries, grouping by country, in your case, it would be
data['userInfo']
and the data of this list is something like this:The first thing is to group by country, and add each state to a dictionary list by country:
What remains is to rearrange the data so that they respect the expected format: