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
  • 40,134
  • 6
  • 50
  • 93
Houy Narun
  • 1,557
  • 5
  • 37
  • 86
  • `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

6

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
  • 40,134
  • 6
  • 50
  • 93
  • thanks very much it's working fine :) – Houy Narun Jan 30 '18 at 11:11
  • This shouldn't be accepted, since the input string uses single quotes, not double quotes. The answers using `ast.literal_eval()` are correct. – Barmar Aug 18 '23 at 15:32
  • @Barmar, but also I think we need to take into account that the OP wanted to use `json.` The error on quotes is explained in the answer as well :) – Netwave Aug 21 '23 at 12:24
  • Unless they have control over the source data, what they "want" is irrelevant. They're stuck with what they get. – Barmar Aug 21 '23 at 15:24
3

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
  • 159,742
  • 34
  • 281
  • 339
1
>>> import ast
>>> s = "{'h':'hello'}"
>>> ast.literal_eval(s)
{'h': 'hello'}
jamylak
  • 128,818
  • 30
  • 231
  • 230
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,753
  • 4
  • 20
  • 37
Alex Ozerov
  • 988
  • 8
  • 21
  • 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