[英]parse json from txt file not working in python
我正在嘗試從 python 中的 txt 文件中提取數據,這是一個 json 轉儲。 但我收到JSONDecode 錯誤
這就是我將 json 響應添加到文件中的方式
repo=requests.get(url,headers=headers,params=params).json()
if repo:
with open('data.txt', 'a') as f:
json.dump(repo, f, sort_keys=True, indent=4)
continue
else:
break
這是我的 json 結構
[
{
"login": "asu",
"login_name": "heylo"
},
{
"login": "sr9",
"login_name": "heylo"
}
],
[
{
"login": "tokuda109",
"login_name": "mojombo"
},
{
"login": "svallory",
"login_name": "mojombo"
}
]
這是我要提取的
with open('data.txt') as fd:
json_data = json.load(fd)
pprint(json_data)
正如評論中所提到的,只是將 JSON 對象一個接一個地連接到一個文件中並不能生成一個有效的 JSON 文件(並且可以將其解析為單個 Z0ECD11C1D7A287401D148A2F8Z 對象)。
最小更好的格式是 JSON Lines, https://jsonlines.org/ ,這是一個文件,每個文件都是一個 JSON 文檔。
您可以通過附加到文件來創建這樣的文件,同時確保在轉儲 JSON 時關閉indent
:
with open('data.txt', 'a') as f:
print(json.dumps(repo, sort_keys=True), file=f)
使用print()
確保尾隨換行符。
然后,您可以使用例如加載數據
with open('data.txt') as fd:
json_data = [json.loads(line) for line in fd if line.strip()]
如果連接 JSON 文檔的當前文件對您很重要,您可以嘗試使用 hack 修復它,例如用[
和]
包裝文件的內容並在其他格式錯誤的連接文檔之間添加逗號,但這並不能保證有效。
with open('data.txt') as fd:
fixed_json_data = json.loads("[" + fd.read().replace("}{", "},{") + "]")
如如何將 append 數據寫入 json 文件中所述? , a
模式不是一個好的選擇,我認為append 手動將數據提取到data.txt
中的可用列表中更好,如下所示:
import json
import requests
def read_content(): # reads and returns the available list in data.txt
try:
with open('data.txt') as fd:
json_data = json.load(fd)
except:
json_data = [] # handle the first write, when the file does not exist
return json_data
url = 'https://api.github.com/users/sferik/followers?per_page=100&page=1'
repo = requests.get(url).json() # repo is a list
if repo:
available_content = read_content() # read available list in data.txt
available_content.extend(repo) # extend new list to the end of available list
with open('data.txt', 'w') as f: # write again, the mode is 'w'
json.dump(repo, f, sort_keys=True, indent=4)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.