0

Still learning python. I'm building a IPFS hash description master list. Every time I create a new IPFS hash I can then add the hash with a description to this list that I can search at a later date to find the specific hash. I'm also trying to make sure that before I add a new hash that the same existing hash does not already exist in the JSON file. Any help would be greatly appreciated and I can learn how to expand on this in the future.

This is the JSON file that I have and will be searching, adding to and deleting from.

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

I can add to this list with new hashes that are created but, I'm unable to search the existing hash list to find a hash or to make sure a new hash is not entered twice.

#!/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...        
Troy Wilson
  • 79
  • 2
  • 10

1 Answers1

1

Since I don't see the importance of order of entry into the list, I'd rather get rid of the list and use a dictionary in stead. That way I wouldn't have to iterate through the list and search for existence of a 'hash-val'.
And assuming the hash_values are unique, I would have the structure as follows:

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



That way, while inserting a new entry, I can easily query on the dictionary if the hash-value or simply the 'key' exists or not.
Something like:

if new_hash_val not in data["hashlist"]:
    #proceed with adding entry
    data["hashlist"][new_hash_val] = {"description":"..." , "url":"..."}
murphy1310
  • 647
  • 1
  • 6
  • 13
  • That would be great! I now have to figure out how to retool the JSON file and also retool the original script. – Troy Wilson Feb 23 '18 at 00:25
  • Any ideas on how to create an object with string containing multiple string:value pairs rather than an object with array of string:value pairs. @murphy1310 – Troy Wilson Feb 23 '18 at 01:33
  • Im sorry I didnt quite get your question. If you are talking about the description and url being assigned to the new_hash_val key in the dictionary, then let me tell you that it is a dictionary in itself and not an array. It has its own key value pairs.. – murphy1310 Feb 26 '18 at 17:55