【问题标题】:Python unable to loop/search for existing JSON entryPython 无法循环/搜索现有的 JSON 条目
【发布时间】:2018-08-02 15:08:49
【问题描述】:

还在学习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...        

【问题讨论】:

    标签: python json python-2.7 ipfs


    【解决方案1】:

    由于我没有看到进入列表的顺序的重要性,我宁愿摆脱列表并改用字典。这样我就不必遍历列表并搜索“哈希值”的存在。
    并假设 hash_values 是唯一的,我的结构如下:

    {
    "hashlist": {
            "QmVZATT8jWoCsNKzy2V3kwBrGXBjuKfifvrE" : {
                                                        "description": "Test Video",
                                                        "url": ""
                                                    },
            "QmVqpEomPZBgQ8dU8cpNezxZHG2oc3xQi61P2n" : {
                                                        "description": "Cat Photo",
                                                        "url": ""
                                                    },
            "QmYdWbq65R4CdFqWGYnPA7V12bX7hf2zxv64AG" : {
                                                        "description": "Test Dir",
                                                        "url": ""
                                                    }
        }
    }
    



    这样,在插入新条目时,我可以轻松地查询字典是否存在哈希值或“键”是否存在。
    比如:

    if new_hash_val not in data["hashlist"]:
        #proceed with adding entry
        data["hashlist"][new_hash_val] = {"description":"..." , "url":"..."}
    

    【讨论】:

    • 那太好了!我现在必须弄清楚如何重组 JSON 文件并重组原始脚本。
    • 关于如何使用包含多个字符串:值对的字符串而不是具有字符串:值对数组的对象创建对象的任何想法。 @murphy1310
    • 对不起,我没有完全明白你的问题。如果您正在谈论分配给字典中 new_hash_val 键的描述和 url,那么让我告诉您它本身就是字典而不是数组。它有自己的键值对..
    猜你喜欢
    • 2016-05-16
    • 1970-01-01
    • 1970-01-01
    • 2016-08-22
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-04-22
    相关资源
    最近更新 更多