[Python learning] Json processing

json is a data type of Key-Value data structure common to all languages, much like a dictionary in Python. In Python, json strings and dictionaries can be converted through the json module.

1. Convert the dictionary to a json string

Copy code
1 import json 
 2 dic = {'zll': { 
 3 'addr': 'Beijing', 'age': 28}, 
 4 'ljj': { 
 5 'addr': 'Beijing', 'age': 38} 
 6 } 
 7 res = json.dumps (dic, ensure_ascii = False, indent = 5) # Turn the dictionary into a json string 
 8 # ensure_ascii = False Chinese is displayed in Chinese, if not, Chinese is displayed as encode 
 9 # indent = 5 5 cells 
10 print (res)
Copy code

 2. Convert the dictionary to json and write it to the file (json.dumps)

Copy code
1 import json 
 2 dic = { 
 3 'zll': { 
 4 'addr': 'Beijing', 
 5 'age': 28 
 6}, 
 7 'ljj': { 
 8 'addr': 'Beijing', 
 9 'age' : 38 
10} 
11} 
12 fw = open ('user_info.json', 'w', encoding = 'utf-8') # open a file 
13 dic_json = json.dumps (dic, ensure_ascii = False, indent = 5) # Dictionary to json 
14 fw.write (dic_json) # Write to file
Copy code

3. json.dump is automatically written to the file

Copy code
1 import json 
 2 dic = { 
 3 'zll': { 
 4 'addr': 'Beijing', 
 5 'age': 28 
 6}, 
 7 'ljj': { 
 8 'addr': 'Beijing', 
 9 'age' : 38 
10} 
11} 
12 fw = open ('user_info.json', 'w', encoding = 'utf-8') # open a file 
13 dic_json = json.dump (dic, fw, ensure_ascii = False, indent = 4) # The dictionary is converted into json, and the file is directly operated without writing
Copy code

4. Use json.loads to convert the json string in the file into a dictionary

1 import json 
2 f = open ('user_info.json', encoding = 'utf-8') 
3 res = f.read () # Use json.loads to read the file first 
4 product_dic = json.loads (res) # put Convert json string to dictionary 
5 print (product_dic)

5. Use json.load without reading the file first, just use it directly

1 import json 
2 f = open ('user_info.json', encoding = 'utf-8') 
3 product_dic = json.load (f) # pass a file object, it will help you read the file 
4 print (product_dic)

6, read / write file content function

Copy code
1 import json 
2 def op_data (filename, dic = None): 
3 if dic: # When dic is not empty, write to the file 
4 with open (filename, 'w', encoding = 'utf-8') as fw: 
5 json.dump (dic, fw, ensure_ascii = False, indent = 4) 
6 else: # When dic is empty, read the file content 
7 with open (filename, 'r', encoding = 'utf-8') as fr: 
8 return json.load (fr)
Copy code

Guess you like

Origin www.cnblogs.com/gtea/p/12715566.html