Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Converting String dictionary like to dictionary [duplicate]

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.

like image 713
Houy Narun Avatar asked Jan 30 '18 10:01

Houy Narun


2 Answers

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

like image 196
Netwave Avatar answered Sep 28 '22 01:09

Netwave


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.

like image 24
jpp Avatar answered Sep 28 '22 02:09

jpp