How does Python use json?

First of all, what does a json look like? You can refer to the reference material, which should look similar to the following:

{
    
    
    "name": "dabao",
    "id":123,
    "hobby": {
    
    
        "sport": "basketball",
        "book": "python study"
    }
}

Does the body look like a Python dictionary? Yes, it's a dictionary when you read it in python. The value of the dictionary can be completely determined by the user, it can be int, float, str or list.

The operation of reading json is as follows (note: json is to be read as text! This reveals the essence, json is essentially a formatted text file! It is often encoded by utf-8, not binary files. ):

import json
 
with open('路径','r', encoding='utf8') as fp:
    json_data = json.load(fp)
    print('这是文件中的json数据:',json_data)
    print('这是读取到文件数据的数据类型:', type(json_data))

(The code here may also be GB code?) The thing read in is a dictionary.

How to write it as a json file?

'''
学习中遇到问题没人解答?小编创建了一个Python学习交流QQ群:531509025
寻找有志同道合的小伙伴,互帮互助,群里还有不错的视频学习教程和PDF电子书!
'''
import json
a = {
    
    
    "name": "dabao",
    "id":123,
    "hobby": {
    
    
        "sport": "basketball",
        "book": "python study"
    }
}
b = json.dumps(a)
with open('new_json.json', 'w') as fp:
    fp.write(b)

The effect is as follows:

insert image description here
First downgrade the dict to a string via json.dumps(). Then write the string to the json file. It's that simple.

Guess you like

Origin blog.csdn.net/sinat_38682860/article/details/120790223
Recommended