I want to save three dictionaries alternately in a json file as an array of objects.
import json milk = {'Product': 'Milk', 'Calories': 100,} bread = {' Product ':' Bread ',' Calories': 200,} fish = {'Product': 'Fish', ' Calories: 300,} def add_food_to_database (food): path = '/home/dzmitry/foods.json' with open (path, 'r +') as jsonfile: if not jsonfile.read (): data = [] data. append (food) json.dump (data, jsonfile) else: jsonfile.seek (0) data = json.load (jsonfile) data.append (food) json.dump (data, jsonfile) print ("Added product:", food ['Product']) foods = (milk, bread, fish) [add_food_to_database (food) for food in foods]
However, for some reason, only two products are added.
=========== RESTART: /home/dzmitry/forstack.py =========== Product added: Milk Product Added: Bread Traceback (most recent call last): File "/home/dzmitry/forstack.py", line 28, in [add_food_to_database (food) for food in foods] File "/home/dzmitry/forstack.py", line 28, in [add_food_to_database (food) for food in foods] File "/home/dzmitry/forstack.py", line 22, in add_food_to_database data = json.load (jsonfile) File "/usr/lib/python3.5/json/__init__.py", line 268, in load parse_constant = parse_constant, object_pairs_hook = object_pairs_hook, ** kw) File "/usr/lib/python3.5/json/__init__.py", line 319, in loads return _default_decoder.decode (s) File "/usr/lib/python3.5/json/decoder.py", line 342, in decode raise JSONDecodeError ("Extra data", s, end) json.decoder.JSONDecodeError: Extra data: line 1 column 140 (char 139) >>>
What am I doing wrong?
[{"Product": "Mikl", "Calories": 100}][{"Product": "Milk", "Calories": 100}, {"Product": "Bread", "Calories": 200}]
, that is, it adds everything, but the format of JSON'a you get is not correct. Should be displayed in the file as -[{"Product": "Milk", "Calories": 100}, {"Product": "Milk", "Calories": 100}, {"Product": "Bread", "Calories": 200}]
- Insiderjson.dump(data, jsonfile)
codejson.dump(data, jsonfile)
appends the file - in addition to the previous data. The file must be rediscovered to create or, at least, unwind to the beginning. - Igor