还在学习python。我正在构建一个 IPFS 哈希描述主列表。每次创建新的 IPFS 哈希时,我都可以将带有描述的哈希添加到此列表中,以便以后搜索以查找特定的哈希。我还试图确保在添加新哈希之前,JSON 文件中不存在相同的现有哈希。任何帮助将不胜感激,我可以学习如何在未来扩展它。
这是我拥有并将搜索、添加和删除的 JSON 文件。
{
"hashlist": [
{
"description": "Test Video",
"ipfsHash": "QmVZATT8jWoCsNKzy2V3kwBrGXBjuKfifvrE",
"url": ""
},
{
"description": "Cat Photo",
"ipfsHash": "QmVqpEomPZBgQ8dU8cpNezxZHG2oc3xQi61P2n",
"url": ""
},
{
"description": "Test Dir",
"ipfsHash": "QmYdWbq65R4CdFqWGYnPA7V12bX7hf2zxv64AG",
"url": ""
}
]
}%
我可以将创建的新哈希添加到此列表中,但是我无法搜索现有哈希列表以查找哈希或确保未输入两次新哈希。
#!/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\n >>")
if choice == 'a':
# Add a new hash.
description = raw_input('Enter hash description: ')
ipfsHash = raw_input('Enter IPFS hash: ')
entry = {'description': description , 'ipfsHash': ipfsHash}
# search existing hash listings here
xglobal = 0
for x in data["hashlist"]:
if data["hashlist"][xglobal]["ipfsHash"] == ipfsHash:
print "Hash already exist!"
break
else:
xglobal += 1
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
elif choice == 's':
# Search the current desciptions.
searchTerm = raw_input('Enter search term: ')
file = open('hash.json', 'r')
data = json.load(file)
file.close()
# Search working
sglobal = 0
for x in data["hashlist"]:
if data["hashlist"][sglobal]["description"] == searchTerm:
hash = data["hashlist"][sglobal]["ipfsHash"]
print "Hash Requested:", hash
break
else:
sglobal += 1
# Notes: How JSON is readable
# Show Hashes working !
# print data["hashlist"][0]["ipfsHash"]
# print data["hashlist"][1]["ipfsHash"]
# print data["hashlist"][2]["ipfsHash"]
# etc...
# Show Descriptions working !
# print data["hashlist"][0]["description"]
# print data["hashlist"][1]["description"]
# print data["hashlist"][2]["description"]
# etc...