需要一些幫助。
我有一個 JSON 檔案,它是 Auth0 匯出資料轉儲的結果。每一行都不用逗號分隔。
下面是名為OUTPUT_USER_DUMP.json
{"user_id": "auth0|5f9886ee8e36ac0069e8fc3a","name": "John Smith","email": "[email protected]"}
{"user_id": "auth0|5fa43f699e937f0068c40d8e","name": "Bob Anderson","email": "[email protected]"}
我想要做的是使用python腳本打開這個json轉儲檔案并將內容分配給一個串列變數(下面的例子當串列變數被列印出來時)
[{"user_id": "auth0|5f9886ee8e36ac0069e8fc3a","name": "John Smith","email": "[email protected]"},
{"user_id": "auth0|5fa43f699e937f0068c40d8e","name": "Bob Anderson","email": "[email protected]"}]
有什么幫助嗎?
uj5u.com熱心網友回復:
您可以逐行讀取檔案并將每一行加載為 json 資料:
from json import loads
with open("OUTPUT_USER_DUMP.json", "r") as f2r:
data = [loads(each_line) for each_line in f2r]
print(data)
uj5u.com熱心網友回復:
您可以直接使用 pandas 讀取新行分隔的 JSON 檔案。您還可以使用資料幀上的to_dict函式將其轉換為您請求的格式
代碼
df = pd.read_json('./OUTPUT_USER_DUMP.json', lines=True)
print(df.to_dict('records'))
輸出
[
{'user_id': 'auth0|5f9886ee8e36ac0069e8fc3a', 'name': 'John Smith', 'email': '[email protected]'},
{'user_id': 'auth0|5fa43f699e937f0068c40d8e', 'name': 'Bob Anderson', 'email': '[email protected]'}
]
uj5u.com熱心網友回復:
鑒于:
bad_json='''
{
"user_id": "auth0|5f9886ee8e36ac0069e8fc3a",
"name": "John Smith",
"email": "[email protected]"
}
{
"user_id": "auth0|5fa43f699e937f0068c40d8e",
"name": "Bob Anderson",
"email": "[email protected]"
}'''
您可以使用正則運算式:
import re
import json
t=re.sub(r"\}\s*\{", "},\n{", bad_json)
new_json=rf'[{t}]'
>>> json.loads(new_json)
[{'user_id': 'auth0|5f9886ee8e36ac0069e8fc3a', 'name': 'John Smith', 'email': '[email protected]'}, {'user_id': 'auth0|5fa43f699e937f0068c40d8e', 'name': 'Bob Anderson', 'email': '[email protected]'}]
編輯
您的檔案似乎是單個 JSON 的 LINES。
鑒于:
cat file
{"user_id": "auth0|5f9886ee8e36ac0069e8fc3a","name": "John Smith","email": "[email protected]"}
{"user_id": "auth0|5fa43f699e937f0068c40d8e","name": "Bob Anderson","email": "[email protected]"}
您可以逐行遍歷檔案并隨時解碼:
import json
with open('/tmp/file') as f:
data=[json.loads(line) for line in f]
>>> data
[{'user_id': 'auth0|5f9886ee8e36ac0069e8fc3a', 'name': 'John Smith', 'email': '[email protected]'}, {'user_id': 'auth0|5fa43f699e937f0068c40d8e', 'name': 'Bob Anderson', 'email': '[email protected]'}]
uj5u.com熱心網友回復:
由于檔案物件是可迭代的,在 python 中產生它們的行,您可以撰寫一個函式將每一行作為 JSON 物件處理:
from json import dumps, loads
from typing import Iterable, Iterator
FILENAME = 'OUTPUT_USER_DUMP.json'
def read_json_objects(file: Iterable[str]) -> Iterator[dict]:
"""Yield JSON objects from each line of a given file."""
for line in file:
if line := line.strip():
yield loads(line)
def main():
"""Run the script."""
with open(FILENAME, 'r', encoding='utf-8') as file:
json = list(read_json_objects(file))
print(dumps(json, indent=2))
if __name__ == '__main__':
main()
轉載請註明出處,本文鏈接:https://www.uj5u.com/net/445834.html
上一篇:Stipe,ReactNative,[未處理的承諾拒絕:SyntaxError:JSON決議錯誤:意外的識別符號“錯誤”]
