Reputation: 79
I'm trying to append an existing JSON file. When I overwrite the entire JSON file then everything works perfect. The problem that I have been unable to resolve is in the append. I'm completely at a loss at this point.
{
"hashlist": {
"QmVZATT8jWo6ncQM3kwBrGXBjuKfifvrE": {
"description": "Test Video",
"url": ""
},
"QmVqpEomPZU8cpNezxZHG2oc3xQi61P2n": {
"description": "Cat Photo",
"url": ""
},
"QmYdWb4CdFqWGYnPA7V12bX7hf2zxv64AG": {
"description": "test.co",
"url": ""
}
}
}%
Here is the code that I'm using where data['hashlist'].append(entry) receive AttributeError: 'dict' object has no attribute 'append'
#!/usr/bin/python
import json
import os
data = []
if os.stat("hash.json").st_size != 0 :
file = open('hash.json', 'r')
data = json.load(file)
# print(data)
choice = raw_input("What do you want to do? \n a)Add a new IPFS hash\n s)Seach stored hashes\n >>")
if choice == 'a':
# Add a new hash.
description = raw_input('Enter hash description: ')
new_hash_val = raw_input('Enter IPFS hash: ')
new_url_val = raw_input('Enter URL: ')
entry = {new_hash_val: {'description': description, 'url': new_url_val}}
# search existing hash listings here
if new_hash_val not in data['hashlist']:
# append JSON file with new entry
# print entry
# data['hashlist'] = dict(entry) #overwrites whole JSON file
data['hashlist'].append(entry)
file = open('hash.json', 'w')
json.dump(data, file, sort_keys = True, indent = 4, ensure_ascii = False)
file.close()
print('IPFS Hash Added.')
pass
else:
print('Hash exist!')
Upvotes: 1
Views: 8912
Reputation: 875
Usually python errors are pretty self-explanatory, and this is a perfect example. Dictionaries in Python do not have an append method. There are two ways of adding to dictionaries, either by nameing a new key, value pair or passing an iterable with key, value pairs to dictionary.update(). In your code you could do:
data['hashlist'][new_hash_val] = {'description': description, 'url': new_url_val}
or:
data['hashlist'].update({new_hash_val: {'description': description, 'url': new_url_val}})
The first one is probably superior for what you are trying to do, because the second one is more for when you are trying to add lots of key, value pairs.
You can read more about dictionaries in Python here.
Upvotes: 5