JSON 檔案 [https://drive.google.com/file/d/1Jb3OdoffyA71vYfojxLedZNPDLq9bn7b/view?usp=sharing]
我正在嘗試在 Python 中讀取 JSON 檔案,JSON 檔案與上面的鏈接相同。我寫的代碼如下所示
lst = []
for line in open(json_path,'r'):
lst.append(json.loads(line))
但由于某種原因,我一直有這個錯誤JSONDecodeError: Expecting value: line 2 column 1 (char 1),我想知道我的代碼做錯了什么還是 JSON 檔案中有錯誤?
uj5u.com熱心網友回復:
更新
\n您可以在使用函式之前去掉斷線 ( ) json.loads(感謝@DeepSpace 的評論):
import json
lst = []
for line in open("sample.json",'r'):
stripped = line.strip("\n")
if stripped != "":
lst.append(json.loads(stripped))
lst
您也可以使用ast模塊:
import ast
lst = []
for line in open("sample.json",'r'):
if line.strip("\n") != "":
lst.append(ast.literal_eval(line))
解釋
ast.literal_eval將字串形式的字典或串列(例如"[1,2,3]")更改為 Python 中可用的字典或串列(例如[1,2,3])。
上面兩個代碼的輸出將是:
[{'content': [{'c_id': '002',
'p_id': 'P02',
'source': 'internet',
'type': 'org'},
{'c_id': '003', 'p_id': 'P03', 'source': 'internet', 'type': 'org'},
{'c_id': '005', 'p_id': 'K01', 'source': 'news', 'type': 'people'}],
'doc_id': '7098727',
'id': 'lni001',
'pub_date': '20220301',
'unique_id': '64WP-UI-POLI'},
{'content': [{'c_id': '002',
'p_id': 'P02',
'source': 'internet',
'type': 'org'},
{'c_id': '003', 'p_id': 'P03', 'source': 'internet', 'type': 'org'},
{'c_id': '005', 'p_id': 'K01', 'source': 'news', 'type': 'people'}],
'doc_id': '7098727',
'id': 'lni001',
'pub_date': '20220301',
'unique_id': '64WP-UI-POLI'},
{'content': [{'c_id': '002',
'p_id': 'P02',
'source': 'internet',
'type': 'org'},
{'c_id': '003', 'p_id': 'P03', 'source': 'internet', 'type': 'org'},
{'c_id': '005', 'p_id': 'K01', 'source': 'news', 'type': 'people'}],
'doc_id': '7098727',
'id': 'lni001',
'pub_date': '20220301',
'unique_id': '64WP-UI-POLI'},
{'content': [{'c_id': '012',
'p_id': 'K21',
'source': 'internet',
'type': 'location'},
{'c_id': '034', 'p_id': 'P17', 'source': 'news', 'type': 'people'},
{'c_id': '098', 'p_id': 'K54', 'source': 'news', 'type': 'people'}],
'doc_id': '7097889',
'id': 'lni002',
'pub_date': '20220301',
'unique_id': '64WP-UI-CFGT'},
{'content': [{'c_id': '012',
'p_id': 'K21',
'source': 'internet',
'type': 'location'},
{'c_id': '034', 'p_id': 'P17', 'source': 'news', 'type': 'people'},
{'c_id': '098', 'p_id': 'K54', 'source': 'news', 'type': 'people'}],
'doc_id': '7097889',
'id': 'lni002',
'pub_date': '20220301',
'unique_id': '64WP-UI-CFGT'}]
轉載請註明出處,本文鏈接:https://www.uj5u.com/yidong/445497.html
上一篇:函式的相反回傳
