JSON & Pickle Modules

Source: Internet
Author: User

JSON module

The JSON module provides four functions: dumps, dump, loads, load

#!/usr/bin/env python#-*-coding:utf-8-*-ImportJsondic= {'K1': 1,'K2': 2,'K3': 3}str_dic= Json.dumps (DIC)##序列化: Convert a dictionary to a stringPrint(Type (str_dic), str_dic)#<class ' str ' > {"K1": 1, "K2": 2, "K3": 3}#Note that the string in the dictionary of the string type converted by JSON is represented by ""Dic2 = Json.loads (str_dic)#deserialization: Converts a dictionary of a string format into a dictionaryPrint(DIC2)#{' K1 ': 1, ' K2 ': 2, ' K3 ': 3}#Note that the string in the dictionary of string types to be processed with the JSON loads function must be represented by ""List_dic = [1,['k1:1'],'a','b','C', [[i]]#you can also handle nested data typesStr_dic =json.dumps (list_dic)Print(Type (list_dic), list_dic)#<class ' list ' > [1, [' k1:1 '], ' a ', ' B ', ' C ', [1, 2, 3]]Str_dic2 =json.loads (str_dic)Print(Type (STR_DIC2), Str_dic2)#<class ' list ' > [1, [' k1:1 '], ' a ', ' B ', ' C ', [1, 2, 3]]
Loads and dumps
Importjsonf= Open ('Json_file','W') DiC= {'K1':'v1','K2':'v2','K3':'v3'}json.dump (dic,f)#The dump method receives a file handle and translates the dictionary directly into a JSON string to write to the fileF.close () F= Open ('Json_file') Dic2= Json.load (f)#The load method receives a file handle, directly converting the JSON string in the file into a data structure to returnf.close ()Print(Type (DIC2), dic2) load and dump
load and dump
Importjsonf= Open ('file','W') Json.dump ({'Nationality':'China'},f) ret= Json.dumps ({'Nationality':'China'}) f.write (ret+'\ n') Json.dump ({'Nationality':'United States'},f,ensure_ascii=False) ret= Json.dumps ({'Nationality':'United States'},ensure_ascii=False) f.write (ret+'\ n') F.close ()
ensure_ascii keyword Parameters
Serialize obj to a JSON formatted str. (string representation of the JSON object) Skipkeys: The default value is False if the data in the Dict keys is not the basic type of Python (Str,unicode, Int,long,float,bool,none), when set to False, the TypeError error is reported. When set to true, this type of key ensure_ascii is skipped: when it is true, all non-ASCII characters are displayed as \uxxxx sequences, just set the ENSURE_ASCII to false at dump. In this case, the Chinese in JSON can be displayed normally. ) If Check_circular isFalse, then the circular reference check forContainer types'll be skipped andA circular reference would resultinchAn Overflowerror (orworse). If Allow_nan isFalse, then it'll be a valueerror-serialize out of range float values (Nan, INF,-inf)inchStrict compliance of the JSON specification, instead of using the JavaScript equivalents (NaN, Infinity,-Infinity). Indent: Should be a non-negative integer, if it is 0 is the Shelf branch display, if empty is the most compact display, otherwise will be wrapped and according to the value of indent displayed in front of the blank branch display, so that the printed JSON data is also called pretty-printed JSON separators: delimiter, which is actually a tuple (item_separator, dict_separator), the default is (', ', ': '), which means "," between Keys in dictionary Separated by a ":" Between key and value. Default (obj) isA function that shouldreturnA serializable version of objor RaiseTypeError. The default simply raises TypeError. Sort_keys: Sorts the data according to the value of keys. To use a custom Jsonencoder subclass (e.g. one, overrides the. Default () method to serialize additional types), Specif Y it with the CLS Kwarg; otherwise Jsonencoder isUsed.
Additional parameter Description
ImportJsondata= {'username':['Li Hua','Erlengzi'],'Sex':'male',' Age': 16}json_dic2= Json.dumps (data,sort_keys=true,indent=2,separators= (',',':'), ensure_ascii=False)Print(JSON_DIC2)
formatted output of JSON

Two modules for serialization

    • JSON, used to convert between string and Python data types
    • Pickle for conversion between Python-specific types and Python data types

The Pickle module provides four functions: dumps, dump (serialize, save), loads (deserialization, read), load (not only serializable dictionary, list ... can serialize arbitrary data types in Python )

ImportPickledic= {'K1':'v1','K2':'v2','K3':'v3'}str_dic=pickle.dumps (DIC)Print(Str_dic)#A string of binary contentDic2=pickle.loads (str_dic)Print(DIC2)#DictionaryImportTimestruct_time= Time.localtime (1000000000)Print(struct_time) F= Open ('Pickle_file','WB') Pickle.dump (struct_time,f) f.close () F= Open ('Pickle_file','RB') struct_time2=pickle.load (f)Print(struct_time2.tm_year)
Pickle

At this time witty you have to say again, since pickle so strong, why still learn JSON?
Here we want to illustrate that JSON is a data structure that all languages can recognize.
If we have a dictionary or serialized into a JSON file, then the Java code or JS code can also be used.
But if we use pickle to serialize, other languages can't read what it is.
So, if your serialized content is a list or a dictionary, we highly recommend that you use the JSON module
But if for some reason you have to serialize other data types, and in the future you will also use Python to deserialize this data, then you can use pickle

JSON & Pickle Modules

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.