This article describes in detail 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 it also uses a habit similar to the C language family (including C, C ++, Java, JavaScript, Perl, Python, and so on ). These features make JSON an ideal data exchange language. Easy to read and write, and easy to parse and generate by machines (generally used to increase the network transmission rate ).
JSON is composed of list and dict in python.
This is the two modules used for serialization:
The Json module provides four functions: dumps, dump, loads, and load.
The pickle module provides four functions: dumps, dump, loads, and load.
Json dumps converts the data type to a string dump converts the data type to a string and stores it in the file loads converts the string to the data type load converts the file open from the string to the 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. josn can only serialize common data types, such as list, dictionary, list, string, number, and object type! Josn won't work. Pickle can serialize all data types, including classes and functions.
Example:
Dumps: converts a dictionary in python to a string.
Import jsontest_dict = {'bigberg ': [7600, {1: [['iPhone', 6300], ['Bike', 800], ['shirt ', 300]} print (test_dict) print (type (test_dict) # dumps converts data into a string json_str = json. dumps (test_dict) print (json_str) print (type (json_str ))
Loads: converts 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 ("loading file completed... ")
Load: open the file and convert the string to the 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 preceding figure shows how to read and write json files using python. For more information, see other related articles in the first PHP community!