Json:json (JavaScript object Notation, JS tag) is a Lightweight data interchange Format (for data serialization and deserialization). (for multiple programming languages, you can exchange data with other programming languages)
Pickle: Used to serialize and deserialize the structure of a Python object. (for Python only)
For humans, JSON is human-readable, and pickle is not.
JSON common methods (support lists, dictionaries, tuples, and other basic data types):
The dumps ()---serializes the incoming object.
Call: Json.dumps (object)
For example (to serialize data that cannot be written directly to a file, such as a list, a dictionary, to a string):
>>> json.dumps ([1,2,3,4])'[1, 2, 3, 4]'>>> json.dumps ({' a'b'c'd ' ': 4})'{"A": 1, "C": 3, "B": 2, "D": 4}'
The dump ()---serializes and writes the incoming object to the file.
Call: Json.dump (object, FP)
For example:
1 ImportJSON2 3List_1 = [1, 2, 3, 4]4Dict_1 = {"a": 1,"C": 3,"b": 2,"D": 4}5 6filename ="Test.json"7 8 " "9 with open (filename, ' W ') as FP:Ten Fp.write (Json.dumps (list_1)) One Fp.write (Json.dumps (dict_1)) A " " - - #equivalent to the code in the above comment thewith open (filename,'W') as FP: - Json.dump (list_1, FP) -Json.dump (dict_1, FP)
View Code
Data in the Test.json file:
{"C""D""b""A ": 1}
Load ()---Load a cup of JSON data stored in the file.
Call: Json.load (FP)
For example (the Json.loads () package, you can see that the data type has not changed since the data was loaded back):
ImportJsonfilename="Test.json"with open (filename,'R') as Fp:dict_1=json.load (FP)Print(Type (dict_1))Print(dict_1)>>> <class 'Dict'>>>> {'b': 2,'a': 1,'D': 4,'C': 3}
Loads ()---load python data.
Call: Json.loads (s) (s refers to data read from a file)
For example (equivalent to read before loading):
Import"test.json"'r') as FP: = fp.read (fp) = json.loads (s) print(type (dict_1)) Print (dict_1)
Pickle common methods (use equivalent to the use of methods in JSON, but pickle support more complex data types, if your data is used only in Python programs, the recommended use of pickle):
Dumps ()---
Dump ()---
Load ()---
Loads ()---
Python---JSON module and pickle module detailed