-4

I am having some real trouble. I have a .txt file with contents like this:

    {'x': '1', 'y': 's'}

And I would like to import this to a dict. I previously used this code, but it doesn't work:

     import json
     database = {}
     f = open('ds.txt','r')
     def load():
             database=json.load(open("ds.txt"))
             print(database)  
     load()

The errors are like this:

    Traceback (most recent call last):
    File "C:\Users\tan\Downloads\Compressed\project2\ct.py", line 11, in <module>
load()
    File "C:\Users\tan\Downloads\Compressed\project2\ct.py", line 6, in load
database=json.load(open("ds.txt"))
    File "C:\Users\tan\AppData\Local\Programs\Python\Python35-32\lib\json\__init__.py", line 268, in load
parse_constant=parse_constant, object_pairs_hook=object_pairs_hook, **kw)
    File "C:\Users\tan\AppData\Local\Programs\Python\Python35-32\lib\json\__init__.py", line 319, in loads
return _default_decoder.decode(s)
   File "C:\Users\tan\AppData\Local\Programs\Python\Python35-32\lib\json\decoder.py", line 339, in decode
obj, end = self.raw_decode(s, idx=_w(s, 0).end())
   File "C:\Users\tan\AppData\Local\Programs\Python\Python35-32\lib\json\decoder.py", line 355, in raw_decode
obj, end = self.scan_once(s, idx)
   json.decoder.JSONDecodeError: Expecting property name enclosed in double quotes: line 1 column 2 (char 1)

I also tried this, but I don't think it really works:

    database={}
    f=open("ds.txt","r")
    def load():
            o= f.read()
            database=o
            print(database)
    load()

This piece of code belongs to a larger code, so if the whole code is required to answer my question, please tell me. Thank you.

Meh
  • 1
  • 2
  • The error message you're getting says that you need double quotes around the keys in the json dictionary – Peter Wang Jul 11 '16 at 14:53
  • Did you try just using double quotes like the error complains about? – Jacobr365 Jul 11 '16 at 14:53
  • 3
    You can't parse invalid JSON with the JSON module. JSON requires double-quotes around keys, as your error says. How did this data get in the text file in the first place? You should store it properly instead of trying to read out improperly stored data. – Two-Bit Alchemist Jul 11 '16 at 14:53
  • can use `json.loads` if write as `json.dumps` otherwise `ast.literal_eval(reading_buffer_without_unreadable_characters)` – dsgdfg Jul 11 '16 at 14:57

2 Answers2

3

Try this:

import ast
database = {}
f=open("ds.txt", "r")

def load():
    return ast.literal_eval(str(f.read()))

database = load()
print(database['y'])

How do you convert a stringed dictionary to a Python dictionary?

Community
  • 1
  • 1
seby
  • 96
  • 1
  • 4
1

Your JSON string is invalid. Instead of single quotes ('), replace it with double quotes (").

{"x": "1", "y": "s"}
Sean Francis N. Ballais
  • 2,338
  • 2
  • 24
  • 42