Home > Article > Backend Development > How to read and write json files using python
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 conventions 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.
These are two modules used for serialization:
json: used to convert between strings and python data types
pickle: Used to convert between python-specific types and python data types
The Json module provides four functions: dumps, dump, loads, load
The pickle module provides four functions: dumps, dump, loads, load
json dumps converts the data type into a string dump converts the data type into a string and stores it in the file loads string Convert to data type Load converts the file opening from a string to a data type
json 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 won't do it. Pickle can serialize all data types, including classes and functions.
Example:
dumps: Convert a dictionary in python to a 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 a string to a dictionary
new_dict = json.loads(json_str) print(new_dict) print(type(new_dict))dump: Write data into a json file
with open("../config/record.json","w") as f: json.dump(new_dict,f) print("加载入文件完成...")load: Open the file and put the string Convert to 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)
The above is the detailed content of How to read and write json files using python. For more information, please follow other related articles on the PHP Chinese website!