Convert string dictionary to dictionary

I have a line that looks like a dictionary like this:

{"h":"hello"} 

I would like to convert it into a real dictionary according to the instructions here

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

However, I received an error message:

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

AttributeError: object 'str' does not have attribute 'read'

What is wrong for my code and how do I convert a string like a dictionary into a real dictionary? Thanks.

+5
source share
4 answers

You want to use loads instead of load :

 json.loads(s) 

loads takes a string as an input string, and load takes a revisited object (basically a file)

Json also uses double quotes to quote '"'

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

There is a living example here.

+7
source

I prefer ast.literal_eval for this:

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

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

+2
source
 >>> import ast >>> s = "{'h':'hello'}" >>> ast.literal_eval(s) {'h': 'hello'} 
+1
source

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

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

For more information on eval see W3school's explanation of eval()

Disclaimer: If you are creating a website for a wide group of users, inform Risks of injection of eval code before using it .

0
source

Source: https://habr.com/ru/post/1275037/


All Articles