0

I'm having strange issues with json. The following program opens a file, imports a dictionary, adds entries, and saves the dictionary again. When the program is run a second time, a letter "u" has been added in front of every key and every value of the dictionary. These are not cumulative; running the program multiple times does not add multiple "u"s.

import json
file1 = open('phonebook.txt', 'r+')
phonebook = json.load(file1)
print phonebook
while(True):
    name = raw_input("Name?")
    if name == "":
        break
    number = raw_input("Number?")
    phonebook[name] = number
file1.close()
file1 = open('phonebook.txt', 'w')
json.dump(phonebook, file1)
print phonebook

Incidentally, an unrelated peculiarity: I get error messages unless I close and reopen the file in write mode. I don't know why this is happening.

HGNY
  • 13
  • 5
  • 1
    use dumps (to dump it as a string, not object) and the u'' prefix is telling you that it is unicode data. – Mike McMahon Feb 01 '16 at 20:27
  • Incidentally, the stored file has the correct dictionary. The addition must be happening in the json.load() process. – HGNY Feb 01 '16 at 20:31
  • @HGNY: The addition happens in the `print`, actually, specifically in `unicode.__repr__`, which is called from `dict.__repr__`. – Kevin Feb 01 '16 at 20:31
  • the additional `u''` does not affect the data or how it is processed, it is simply how it is loaded (unicode string) vs. a regular string. – Mike McMahon Feb 01 '16 at 20:32
  • Aha -- so I could keep using the original code! – HGNY Feb 01 '16 at 20:43

2 Answers2

2

The u stands for unicode "string". For a more detailed answer look here What does the 'u' symbol mean in front of string values?

Community
  • 1
  • 1
Stefan Reinhardt
  • 622
  • 8
  • 17
0

OK - thanks. This seems to work:

import json
file1 = open('phonebook.txt', 'r')
phonebook = eval(file1.read())
while(True):
    name = raw_input("Name?")
    if name == "":
        break
    number = raw_input("Number?")
    phonebook[name] = number
file1.close()
file1 = open('phonebook.txt', 'w')
file1.write(json.dumps(phonebook))
file1.close()
HGNY
  • 13
  • 5