0

I have a dictionary in python. I want to modify that dictionary and then save the dictionary to an external file so that when I load up the python program again it grabs the dictionary data from the external file.

class Data:
"""
Data handling class to save
and receive json data, parent
of User for data  purposes.
"""
def saveData(data, file):
    with open(file, 'r+') as dataFile:
        dataFile.write(json.dumps(data))

def getData(file):
    with open(file, 'r+') as dataFile:
        return json.loads(dataFile.readline())

def deleteContent(file):
    file.seek(0)
    file.truncate()

But when I write to the file and then try to read it reads it as a string and I can't use the read data to set a dictionary. How can I get data in a dictionary from an external JSON file as dictionary data, not string data?

data = Data.getData("chatbotData.json")
dataDict = data
dataDict["age"] = 2

Here is what I want to do with the data and I get this error:

TypeError: 'str' object does not support item assignment

  • First try to use `json.dump(dataFile, data)` (or argument order switched, I can never remember and `return json.load(dataFile)`. Also why not just use `r` and `w` file modes? – Martin Ueding Nov 30 '17 at 07:44

1 Answers1

3

Let's create a dictionary:

>>> d = {'guitar':'Jerry', 'drums':'Mickey' }

Now, let's dump it to a file:

>>> import json
>>> json.dump(d, open('1.json', 'w'))

Now, let's read it back in:

>>> json.load(open('1.json', 'r'))
{'guitar': 'Jerry', 'drums': 'Mickey'}

Taking better care of file handles

The above illustrates the json module but was sloppy about closing files. Better:

>>> with open('1.json', 'w') as f:
...     json.dump(d, f)
... 
>>> with open('1.json') as f:
...     json.load(f)
... 
{'guitar': 'Jerry', 'drums': 'Mickey'}
John1024
  • 109,961
  • 14
  • 137
  • 171
  • `json.decoder.JSONDecodeError: Expecting value: line 1 column 1 (char 0)` –  Nov 30 '17 at 07:51
  • 1
    @DNinja21 I just copied-and-pasted from my answer to the python command prompt and it all works fine for me. Are you running exactly the same commands or have you modified them? Which command gave you that error? – John1024 Nov 30 '17 at 07:53
  • writing the json works fine but reading it gives this error, I'll give ut another try. –  Nov 30 '17 at 07:55
  • 1
    Thanks, @John1024 I retested it and now it works fine. –  Nov 30 '17 at 07:58