[英]Using Variables from Python Script when Importing JSON
我有一個帶有以下代碼的 Python 文件main.py
,但它給了我錯誤消息:
day_of_event = '1990-12-25'
shopping_list = ['bread', 'cereal', 'water', 'soda', 'bananas']
with open(store_items.json) as file:
json_file = json.loads(file)
report = json_file["report"]
report = json.dumps(report)
以下是 JSON 文件store_items.json
:
{
"report" : "{'title' : 'grocery_report', 'date' : day_of_event, 'grocery_items' : shopping_list}"
}
How can I read the JSON file store_items.json
and import the JSON variable "report" into the Python file so that the variable report
in the Python script is equivalent to the following?
report = {'title' : 'grocery_report', 'date' : '1990-12-25', 'grocery_items' : ['bread', 'cereal', 'water', 'soda', 'bananas']}
要直接從文件中讀取,您需要json.load
而不是json.loads
; s
代表“字符串”,您正在從文件而不是字符串中讀取。 (我同意這些名稱可以而且應該更好。)另外,您的文件名需要被引用。 處理完之后, report = json_file["report"]
已經為您提供了您想要的結果。 ( .dumps
調用轉換回字符串 - 再次, s
表示字符串,而不是寫入打開的文件 object - 因此不是您想要的。)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.