This article mainly introduces the mutual conversion of Python string str and json format. When converting str to json format, the prerequisite must be to ensure that the format of this str is consistent with json. Below, the editor of Weidian Reading will introduce more relevant content to you. Friends in need can refer to it.
Introduction:
str
To convert to json
format, the prerequisite must be to ensure that the format of this str is consistent with json, that is, the outermost layer on the left is braces, and the outermost layer on the right is braces. If they are inconsistent, it is recommended to use regular expressions to split them into the same json format.
1. Convert via json.loads
1 2 3 4 5 |
|
json
Internal data needs to be surrounded by double quotes, single quotes cannot be used
2.json to str
The method used json.dumps
can json
convert the object into a string
1 2 3 4 5 6 |
|
3. Pass eval
The official explanation of the eval function is: treat the string str as a valid expression to evaluate and return the calculation result.
That is, eval can be used to convert list
, tuple
, dict
and string
into each other, for example:
1 2 3 4 5 6 7 8 9 10 11 12 |
|
result:
<class 'list'>
<class 'dict'>
<class 'tuple'>
This concludes this article on the conversion of Python string str and json formats. I hope it can be helpful to you.