python - 从 JSON 文件末尾删除空 {}
问题描述
我的代码发出一个 json 请求,然后将数据输出到一个 json 格式的文件,但文件末尾带有空的 {} 或 []。这是发出请求的代码:
for rt in requestType:
limit = 1000
offset = 0
page = 0
request = request_str.get(url+rt+'?limit='+str(limit)+'&offset='+str(offset))
data = request.json()
total_count = request.headers['X-Total-Count']
pages = math.ceil(int(total_count) / limit)
fileName = rt.replace("/","")+".json"
with open(fileName, 'w') as outf:
json.dump(data, outf, indent=4)
while (page) < pages:
offset = offset + limit
request = request_str.get(url+rt+'?limit='+str(limit)+'&offset='+str(offset))
data = request.json()
with open(fileName, 'a') as outf:
json.dump(data, outf, indent=4)
page += 1
以下是 json 文件的示例:
{
"orgs": [
{
"sourcedId": "04EB8C87-7B48-474A-9404-4E352FE3207E",
"status": "active",
"dateLastModified": "2020-06-25T19:51:00.000Z",
"name": "name of org",
"type": "building",
"identifier": "0157",
}
]
},{
"orgs": []
}
如何{"orgs": []}
从文件末尾删除?或者更好的是,我怎样才能防止它首先被写入文件?
解决方案
Add logic that only write if the length of the data is greater than 0:
for rt in requestType:
limit = 1000
offset = 0
page = 0
request = request_str.get(url+rt+'?limit='+str(limit)+'&offset='+str(offset))
data = request.json()
total_count = request.headers['X-Total-Count']
pages = math.ceil(int(total_count) / limit)
fileName = rt.replace("/","")+".json"
with open(fileName, 'w') as outf:
json.dump(data, outf, indent=4)
while (page) < pages:
offset = offset + limit
request = request_str.get(url+rt+'?limit='+str(limit)+'&offset='+str(offset))
data = request.json()
if len(data['orgs']) > 0: #<-- if data len greater than 0, append it
with open(fileName, 'a') as outf:
json.dump(data, outf, indent=4)
page += 1