Four json functions
function | |
---|---|
() | Read the local json data file and return a string in JSON format from the file object in a list form, and deserialize it into a Python object |
() | Deserialize JSON-formatted strings into Python objects |
() | Serialize the Python object into a JSON format string and write it to the file object. |
() | Serialize Python objects into strings in JSON format |
Save data locally as json files
use()
Instance data
class Person: name = None age = None def __init__(self, name, age): = name = age person1 = Person("Alice", 30) person2 = Person("Bob", 25) person3 = Person("Charlie", 35) person4 = Person("David", 28) person5 = Person("Eve", 32) persons = [person1, person2, person3, person4, person5] person_list = [person.__dict__ for person in persons] print(person_list) ''' [{'name': 'Alice', 'age': 30}, {'name': 'Bob', 'age': 25}, {'name': 'Charlie', 'age': 35}, {'name': 'David', 'age': 28}, {'name': 'Eve', 'age': 32}] <class 'list'> Returns a list '''
object.__dict__
object.__dict__
is a special property in Python that stores instance properties of an object. Each Python object has one__dict__
Properties, it is a dictionary that contains all instance properties of an object and their corresponding values
Save the object's data to json, you need to use it firstObject.__dict__
Take out the dictionary form of each object (using list comprehension), save the dictionary form of each object in the list, and save the list in the json file
data_list = [person.__dict__ for person in persons] # List comprehension
Save data
def load_data(): with open(data_file, 'r', encoding='utf-8') as file: return (file)
Read data
def save_data(persons): with open(data_file, 'w', encoding='utf-8') as file: ([person.__dict__ for person in persons], file, indent=2)
Things to note
The open() function automatically creates a file:
In 'r' mode (read-only mode), if the file does not exist, FileNotFoundError will be directly thrown, and the file will not be created automatically.
It will be automatically created only if the file does not exist when using 'w' (write mode) or 'a' (append mode).
Actual case:
class HouseService: house_list = [] data_file = ((__file__), 'house_data.json') def __init__(self): self.load_data() if not self.house_list: house1 = House('1', 'lihua', '123456', 'Zhengzhou Zhongyuan District', 800, 'Not for rent') house2 = House('2', 'jack', '123452', 'Erqi District, Zhengzhou City', 900, 'Not for rent') self.house_list.append(house1) self.house_list.append(house2) self.save_data() # Load house data def load_data(self): try: with open(self.data_file, 'r', encoding='utf-8') as file: data = (file) self.house_list = [House(**house) for house in data] except FileNotFoundError: self.house_list = [] # Save house data def save_data(self): with open(self.data_file, 'w', encoding='utf-8') as file: ([house.__dict__ for house in self.house_list], file, ensure_ascii=False, indent=4)
In this case,load_data()
If the function does not use exception capture, and there is nohouse_data.json
When the file is filed, the system will directly throw an exception. After the exception is caught and the data list is initialized, the program can continue to proceed downwards tosave_data()
Save data and automatically create json files
Therefore, during the development process, when writing and saving house data, pay attention to exception capture
Add data
If there is new data that needs to be saved, it cannot be used directlymode='a'
, 'a'
Append writes to the pattern will cause the JSON file to becomeMultiple independent objectsInstead of valid arrays, the newly added data will be saved directly outside []
[{...}, {...}] // Raw data{...} // New data added (format error)
Therefore, to append data to the json file, you need to use the following method:
Use the mode of read → modify → overwrite write (rather than append directly)
Use the 'w' pattern to ensure that the complete JSON array structure is written every time
import os import json # Sample datadata = { "name": "Alice", "age": 30, "skills": ["Python", "Docker"], "is_active": True } data_dile = ((__file__), 'person_data.json') def save_data(data): with open(data_dile, 'w', encoding='utf-8') as file: (data, file, indent=2) def load_data(): with open(data_dile, 'r', encoding='utf-8') as file: data = (file) return data exist_data = load_data() # Get existing dataprint(type(exist_data)) # <class 'list'> exist_data.append(data) # Want to add data to the listsave_data(exist_data) # Save the list of data added
This is the introduction to this article about the detailed explanation of Python's built-in json to implement local persistence of data. For more related content on local persistence of Python data, please search for my previous articles or continue browsing the related articles below. I hope everyone will support me in the future!