我想转换下面的json文件:
[
{
"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"
}
]
转换为具有更多列且不重复的csv文件,如下所示:
username,user id,access hash,name,group,group id,is_bot,is_admin,dc_id,have_photo,phone,elaborated
输出文件应为:
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
我尝试了以下代码:
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['userid'] in [x['userid'] for x in target]:
if item['username'] == "None":
item['username'] == ""
record = item['username'] + ',' + item['userid'] + ',' + 'False' + ',' + 'False' + ',' + 'False' + ',' + 'False' + ',' + 'False' + ',' + 'False' + ',' + 'False' + ',' + 'False' + ',' + 'False' + ',' + 'False'
nf.write(json.dumps(record).replace('"', '') + '\n') # write data without ""
它不起作用,因为错误是由项['user-id'](带有空格的用户id不起作用)生成的,但项['userid']起作用。
我该怎么解决这个问题?
根据Barmar的建议,我更新了以下代码:
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['userid'] in [x['userid'] for x in target]:
if item['username'] == "None":
item['username'] == ""
record = item['username'] + ',' + item['userid'] + ',' + 'False' + ',' + 'False' + ',' + 'False' + ',' + 'False' + ',' + 'False' + ',' + 'False' + ',' + 'False' + ',' + 'False' + ',' + 'False' + ',' + 'False'
nf.write(json.dumps(record).replace('"', '') + '\n') # write data without ""
然而,还有另一个问题即将出现,这并不是有意的。当target_user2.json中username为None时,我将其分配为blank:
item['username'] == ""
它不起作用;它从targetuser2.json中写入具有相同值的所有用户名。
这是怎么回事?