1

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!')
Troy Wilson
  • 79
  • 2
  • 10
  • Python dictionaries don't have `append` method. Write `data['hashlist'] = entry` instead. – Nurjan Feb 23 '18 at 03:18
  • 1
    Or `data['hashlist'].update(entry)`, perhaps. – Robᵩ Feb 23 '18 at 03:18
  • The data['hashlist'].update(entry) worked. The = entry just does a full overwrite and is listed in the code. – Troy Wilson Feb 23 '18 at 03:21
  • @TroyWilson `data['hashlist'] = entry` should be `data['hashlist'][new_hash_val] = entry`. For a single key, value pair, you should use this way of assigning values. – Sam Craig Feb 23 '18 at 03:26
  • A side note, `file = open(...)` is bad practice, try `with open()` syntax so that you don't have to manually open and close it every time. – FatihAkici Feb 23 '18 at 03:36
  • Does this answer your question? ['dict' object has no attribute 'append' Json](https://stackoverflow.com/questions/33640689/dict-object-has-no-attribute-append-json) – kaya3 Feb 22 '20 at 13:43

1 Answers1

5

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.

Sam Craig
  • 875
  • 5
  • 16