我正在尝试附加现有的JSON文件。当我覆盖整个JSON文件时,一切都将正常运行。我无法解决的问题在附录中。在这一点上,我完全不知所措。
{
"hashlist": {
"QmVZATT8jWo6ncQM3kwBrGXBjuKfifvrE": {
"description": "Test Video",
"url": ""
},
"QmVqpEomPZU8cpNezxZHG2oc3xQi61P2n": {
"description": "Cat Photo",
"url": ""
},
"QmYdWb4CdFqWGYnPA7V12bX7hf2zxv64AG": {
"description": "test.co",
"url": ""
}
}
}%
Run Code Online (Sandbox Code Playgroud)
这是我在data ['hashlist']。append(entry)接收AttributeError的地方使用的代码:'dict'对象没有属性'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!')
Run Code Online (Sandbox Code Playgroud)
通常python错误非常容易解释,这是一个完美的例子。Python中的字典没有添加方法。有两种添加字典的方法,一种是命名一个新的键值对,或者将一个带有键的可迭代值对传递给dictionary.update()。在您的代码中,您可以执行以下操作:
data['hashlist'][new_hash_val] = {'description': description, 'url': new_url_val}
Run Code Online (Sandbox Code Playgroud)
要么:
data['hashlist'].update({new_hash_val: {'description': description, 'url': new_url_val}})
Run Code Online (Sandbox Code Playgroud)
第一个可能更适合您尝试做的事情,因为第二个更适合您尝试添加大量键,值对的情况。