How to convert Python string str and json formats to each other

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:

strTo convert to jsonformat, 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

import json

str = '{"name": "成年", "age": 18}'

j = json.loads(str)

print(j)

print(type(j))

jsonInternal data needs to be surrounded by double quotes, single quotes cannot be used

2.json to str

The method used json.dumpscan jsonconvert the object into a string

1

2

3

4

5

6

import json

str = '{"name": "成年", "age": 18}'

j = json.loads(str)

print(j)

j = json.dumps(j)

print(type(j))

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, dictand stringinto each other, for example:

1

2

3

4

5

6

7

8

9

10

11

12

import json

a = "[[1,2], [3,4]]"

b = eval(a)

print(type(b))

  

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

b = eval(a)

print(type(b))

  

a = "([1,2], [3,4], [5,6], (9,0))"

b = eval(a)

print(type(b))

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.

Source: Weidian Reading   https://www.weidianyuedu.com

Guess you like

Origin blog.csdn.net/weixin_45707610/article/details/131782077