简体   繁体   中英

Using Variables from Python Script when Importing JSON

I have a Python file main.py with the following code, but it is giving me error messages:

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)

The following is the JSON file 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']}

To read from the file directly, you need json.load rather than json.loads ; the s stands for "string", and you are reading from a file rather than a string. (I agree that these names can and should be better.) Also, your file name needs to be quoted. After taking care of that, report = json_file["report"] already gives you the result you want . (The .dumps call converts back to string - again, s for string, as opposed to writing into an open file object - and thus is not what you want.)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM