I would like to convert a json file below:
[
{
"userid": "5275800381",
"status": "UserStatus.RECENTLY",
"name": "Ah",
"bot": false,
"username": "None"
},
{
"userid": "5824657725",
"status": "UserStatus.LAST_MONTH",
"name": "A45",
"bot": false,
"username": "None"
},
{
"userid": "5160075986",
"status": "UserStatus.RECENTLY",
"name": "CTLA",
"bot": false,
"username": "james888"
}
]
into a csv file with more columns and without duplicates as follows:
username,user id,access hash,name,group,group id,is_bot,is_admin,dc_id,have_photo,phone,elaborated
The output file should be:
username,user id,access hash,name,group,group id,is_bot,is_admin,dc_id,have_photo,phone,elaborated
,5275800381,False,False,False,False,False,False,False,False,False,False
,5824657725,False,False,False,False,False,False,False,False,False,False
james888,5160075986,False,False,False,False,False,False,False,False,False,False
I have tried the following codes:
import json
with open('target_user2.json', 'r', encoding='utf-8') as fp:
target = json.load(fp) #this file contains the json
with open('members2.csv', 'w', encoding='utf-8') as nf: # target_userid2.txt or target_userid2.json
nf.write('username,user id,access hash,name,group,group id,is_bot,is_admin,dc_id,have_photo,phone,elaborated' + 'n')
for item in target:
if item['user id'] in [x['user id'] for x in target]:
if item['username'] != "None":
item['username'] == ""
record = item['username'] + ',' + item['user id'] + ',' + 'false' + ',' + 'false' + ',' + 'false' + ',' + 'false' + ',' + 'false' + ',' + 'false' + ',' + 'false' + ',' + 'false' + ',' + 'false' + ',' + 'false'
nf.write(json.dumps(record).replace('"', '') + 'n') # write data without ""
it does not work because error is generated by item[‘user id’] (user id with a space not working), but item[‘userid’] works.
How can I fix this?