[英]How do I read json content from python file that I have made into an executable (Mac)
[英]How do I read a .json file that doesn't have [ ]?
我在 Python 中有一個 .json 文件,如下所示:
{
"abc_id": "ABC-2019-1945",
"def_id": "20"
},
{
"abc_id": "ABC-2019-1944",
"def_id": "200"
}
我正在嘗試使用json.load(open(json_path,"r"))
讀取它json.load(open(json_path,"r"))
但它給了我一個錯誤,因為它有多個 .json 對象。
看起來只需在文件開頭添加[
和]
就可以解決問題,但我不知道如何向文件中添加任何我無法讀取的內容(為每個文件手動添加是對我來說是一個糟糕的解決方案)。 我也嘗試將文件作為文本文件讀取,但我不知道如何將 .json 作為文本讀取。
任何人都可以為我的問題建議一個好的解決方案嗎?
錯誤是因為 JSON 無效,不僅因為缺少 [],還因為每個條目中 def_id 鍵末尾的逗號是錯誤的。 每個對象中的最后一個元素不得以逗號結尾。
您可以通過https://jsonlint.com/運行它進行檢查。
有效的
json.loads('[{"abc_id": "ABC-2019-1945", "def_id": "20"}, {"abc_id": "ABC-2019-1944", "def_id": "200"}]')
由於多余的逗號而無效
json.loads('[{"abc_id": "ABC-2019-1945", "def_id": "20",}, {"abc_id": "ABC-2019-1944", "def_id": "200",}]')
所以原始的JSON需要是這個
[
{
"abc_id": "ABC-2019-1945",
"def_id": "20"
},
{
"abc_id": "ABC-2019-1944",
"def_id": "200"
}
]
** 更新 ** 現在問題已修改為包含您可以使用的有效 JSON
with open(json_path,"r") as f:
d = f.read()
json.loads(f"[{data}]")
# or
json.loads("[" + data + "]")
# or
json.loads("[%s]" % data)
# or
json.loads("[{}]" % data)
json模塊提供了兩種解析 JSON 對象的方法(同樣適用於序列化):
這是最終的代碼:
with open(json_path,"r") as f:
data = f.read()
json.loads("["+data+"]")
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.