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.
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
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
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With