[英]What is the most Pythonic way to convert a valid json file to a string?
以下是我目前正在做的事情,只是想知道是否有更好的方法。
with open("sample.json", "r") as fp:
json_dict = json.load(fp)
json_string = json.dumps(json_dict)
with open("sample.json") as f:
json_string = f.read()
無需解析和解析它。
如果需要在無效的JSON上引發異常,則可以解析該字符串並跳過解析它的工作:
with open("sample.json") as f:
json_string = f.read()
json.loads(json_string) # Raises an exception if the JSON is invalid.
Json文件只是一個常規文件。 您open()
並read()
。 它會給你一個str
。 如果要確保它包含有效的JSON,請將上述代碼的load
部分放入try/except
塊中。
我不知道它是Pythonic還是毫無意義,但如果驗證是您的要求的一部分,您也可以這樣做:
import json
# I'm fully aware of the missing "ẁith" or "close" in the line below
json_string = json.dumps(json.load(open('sample.json')))
否則,user2357112已經說過: “無需解析和解析。”
您做對了。 您可能會發現一些具有不同實現的庫,這些庫具有特定的性能或內存優化特性。 python標准可靠,涵蓋大多數情況,可以確保與其他平台兼容並且非常簡單。 它不能獲得比這更多的pythonic。
如果您只需要讓它引發無效JSON的Exception,那么這樣做的方式就可能很好。 但是,如果要確保完全不更改文件,可以嘗試執行以下操作:
import json
with open("sample.json") as fp:
json_string = fp.read()
json.loads(json_string)
如果它是無效的JSON,它仍然會引發ValueError,並且您知道您根本沒有更改數據。 如果您想知道可能會發生什么變化,請讓我煩惱:dict項的順序和空格,更不用說JSON中是否有重復的鍵。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.