5

I have string that looks like dictionary like this:

{"h":"hello"}

I would like to convert it to an actual dictionary as instructed here

>>> import json
>>> 
>>> s = "{'h':'hello'}"
>>> json.load(s)

Yet, I got an error:

Traceback (most recent call last): File "", line 1, in File "/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/json/init.py", line 286, in load return loads(fp.read(),

AttributeError: 'str' object has no attribute 'read'

What is wrong to my code, and how I convert string like dictionary to actual dictionary? Thanks.

Netwave
  • 36,219
  • 6
  • 36
  • 71
Houy Narun
  • 1,442
  • 3
  • 32
  • 68
  • `json.load` is for a file, but thats not valid `json` anyway so `json.loads` wont work – jamylak Jan 30 '18 at 10:56
  • For person who voted to close as typo: This is not off topic typo because it is valid python, just not valid json – jamylak Jan 30 '18 at 11:00

4 Answers4

7

You want to use loads instead of load:

json.loads(s)

loads take as input an string while load takes a readeable object (mostly a file)

Also json uses double quotes for quoting '"'

s = '{"a": 1, "b": 2}'

Here you have a live example

Netwave
  • 36,219
  • 6
  • 36
  • 71
2

I prefer ast.literal_eval for this:

import ast

ast.literal_eval('{"h":"hello"}')  # {'h': 'hello'}

See this explanation for why you should use ast.literal_eval instead of eval.

jpp
  • 147,904
  • 31
  • 244
  • 302
1
>>> import ast
>>> s = "{'h':'hello'}"
>>> ast.literal_eval(s)
{'h': 'hello'}
jamylak
  • 120,885
  • 29
  • 225
  • 225
0

The eval function allows you to run code and use the result. It is typically used to interprete a string as code.

string = '{"a": 1, "b": 2}'
dct = eval(string)

For more information on eval, see the W3school explanatino on eval()

Disclaimer: if you are building a website for a broad user group, inform yoursel fon Code injection risks of eval before using it.

Dirk Horsten
  • 3,467
  • 4
  • 19
  • 35
Alex Ozerov
  • 890
  • 7
  • 20
  • 1
    If you look in the duplicate: https://stackoverflow.com/a/988251/1219006 It states not to use `eval` – jamylak Jan 30 '18 at 11:03