[Python stores and calls json files]


foreword

Many programs require the user to enter some kind of information, and programs typically store the information in data structures such as lists and dictionaries.

When the user closes the program, the information needs to be saved. A simple way is to use the module json to store the data.

The module json enables you to dump simple Python data structures into a file and load the data from that file when the program is run again.

You can also use json to share data between Python programs. More importantly, data files in JSON (JavaScript Object Notation, originally developed by JavaScript) format can be compatible with many programming languages.

basic concept

1. json.dumps() and json.loads() are json format processing functions (it can be understood that json is a string)

  • The json.dumps() function encodes a list of Python data types in json format (it can be understood that the json.dumps() function converts a dictionary into a string)
  • The json.loads() function converts json format data into a dictionary (it can be understood that the json.loads() function converts a string into a dictionary)

2. json.dump() and json.load() are mainly used to read and write json file functions

1. json.dumps()

import json

# json.dumps()函数的使用,将字典转化为字符串
dict1 = {
    
    "age": "12"}
json_info = json.dumps(dict1)
print("dict1的类型:"+str(type(dict1)))
print("通过json.dumps()函数处理:")
print("json_info的类型:"+str(type(json_info)))

operation result:
Please add a picture description

2. json.loads()

import json

# json.loads函数的使用,将字符串转化为字典
json_info = '{"age": "12"}'
dict1 = json.loads(json_info)
print("json_info的类型:"+str(type(json_info)))
print("通过json.dumps()函数处理:")
print("dict1的类型:"+str(type(dict1)))

Please add a picture description

3. json.dump()

import json

# json.dump()函数的使用,将json信息写进文件
json_info = "{'age': '12'}"
file = open('1.json','w',encoding='utf-8')
json.dump(json_info,file)

Run the screenshot (1.json file):
Please add a picture description

4. json.load()

import json

# json.load()函数的使用,将读取json信息
file = open('1.json','r',encoding='utf-8')
info = json.load(file)
print(info)
# {'age':'12'}

5. Comprehensive application of json

import json

# list 转成Json格式数据
def listToJson(lst):
    keys = [str(x) for x in np.arange(len(lst))]
    list_json = dict(zip(keys, lst))
    #  # indent,格式化保存字典,默认为None,小于0为零个空格
    str_json = json.dumps(list_json, indent=2, ensure_ascii=False)  # json转为string
    return str_json

rawList = [1, 3, 4, 7]
# 保存JSON
numbers = listToJson(rawList)
filename = "numbers.json" # 默认保存到根目录下,指定存储数据的文件名称
with open(filename, 'w') as file_obj:
  json.dump(numbers, file_obj)

# 加载JSON
filename = "numbers.json"
with open(filename) as file_obj:
  numbers = json.load(file_obj)
print(numbers) # 打印JSON

# 运行结果
"""
{
  "0": 1,
  "1": 3,
  "2": 4,
  "3": 7
}
"""
  1. rawList converts the list into Json format data through the listToJson function;
  2. Open numbers.json with the open function, and call json.dump( ) to store the data;
  3. Open the file in read-only mode;
  4. json.load( ) loads the information in the file and stores it in the variable numbers;
  5. Print the digital information in numbers;

References

Blog Garden: The distinction between the four functions json.dumps() and json.loads(), json.dump() and json.load() involved in json file processing in python
Script House: How Python stores data to json files

Guess you like

Origin blog.csdn.net/weixin_43849871/article/details/120513773