This time I will bring you a detailed explanation of the case of reading and writing json files in python (with code). What are the precautions for reading and writing json files in python? The following is a practical case, let's take a look.
JSON(JavaScript Object Notation) is a lightweight data exchange format. It is based on a subset of ECMAScript. JSON uses a completely language-independent text format, but also uses habits similar to the C language family (including C, C, Java, JavaScript, Perl, Python, etc.). These properties make JSON an ideal data exchange language. It is easy for humans to read and write, and it is also easy for machines to parse and generate (generally used to increase network transmission rates).
JSON consists of list and dict respectively in python. Here are two modules for serialization:strings and pythondata typesConvert between
type into characters String dump converts the data type into a string and stores it in the file loads converts the string into a data type load opens the file and converts the string into a data typejson can exchange data between different languages , while pickle is only used between python. JSON can only serialize the most basic data types, and JSON can only serialize commonly used data types (lists, dictionaries, lists, strings, numbers, etc.), such as date formats and class objects! Josn can't do it. Pickle can serialize all data types, including classes and functions.
Example:dumps: Convert dictionary in python to string
import json test_dict = {'bigberg': [7600, {1: [['iPhone', 6300], ['Bike', 800], ['shirt', 300]]}]} print(test_dict) print(type(test_dict)) #dumps 将数据转换成字符串 json_str = json.dumps(test_dict) print(json_str) print(type(json_str))
loads: Convert string to dictionary
new_dict = json.loads(json_str) print(new_dict) print(type(new_dict))
dump: Write data into json file
with open("../config/record.json","w") as f: json.dump(new_dict,f) print("加载入文件完成...")
load: Write the file Open and convert the string into a data type
with open("../config/record.json",'r') as load_f: load_dict = json.load(load_f) print(load_dict) load_dict['smallberg'] = [8200,{1:[['Python',81],['shirt',300]]}] print(load_dict) with open("../config/record.json","w") as dump_f: json.dump(load_dict,dump_f)
I believe you have mastered the method after reading the case in this article. For more exciting information, please pay attention to other related articles on the PHP Chinese website!
Recommended reading:
Summary of cases using JSONPHow to use json as a parameter in jsThe above is the detailed content of Detailed explanation of python reading and writing json files (with code). For more information, please follow other related articles on the PHP Chinese website!