1

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']}
bluetree8173
  • 59
  • 2
  • 5
  • You need to put quotes around your filename 'store_items.json' in open and make sure that you are in the same folder. You can use os.path.abspath(os.curdir) to check where your current directory is. If it is different than where 'store_items.json' is you will need to provide the absolute path to the file. – Willie D Sep 26 '19 at 21:32
  • Try using json.load() instead of json.loads(): `with open('store_items.json') as file: data = json.load(file)['report']` – Anil Sep 26 '19 at 21:52
  • See [this post](https://stackoverflow.com/questions/39719689/what-is-the-difference-between-json-load-and-json-loads-functions) for details – Anil Sep 26 '19 at 21:55
  • 2
    The contents of the JSON file don't make sense. The value of `report` is a string that looks like a Python literal. But it contains variable names -- are you expected to use `eval()` to process it? That seems like very poor design. – Barmar Sep 26 '19 at 22:03
  • @Barmar I think it is more likely that the example file contents have been incorrectly reproduced here, than that the actual file is wrong. – Karl Knechtel Sep 26 '19 at 22:04

1 Answers1

1

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.)

Karl Knechtel
  • 62,466
  • 11
  • 102
  • 153