Serialized json, pickle, and jsonpickle in python

Source: Internet
Author: User

Serialized json, pickle, and jsonpickle in python

What is Json:

JSON (JavaScript Object Notation) is a lightweight data exchange format. Easy for reading and writing, and easy for machine parsing and generation. Json uses a completely language-independent text format, but it also uses family habits similar to C language (such as C, C ++, C #, Java, JavaScript, Perl, Python, etc ), these features make Json an ideal exchange language. Generally, it processes simple data objects and interacts with each other.

For simple data types, encoding and decoding:

### Encoding >>> import json >>> obj = [[1, 2, 3], ('A', 'B', 'C'), {'4 ': 5, '6': 7}, 'def '] >>> encoding_json = json. dumps (obj) >>> print (encoding_json) [[1, 2, 3], ["a", "B", "c"], {"4 ": 5, "6": 7}, "def"] # note that the tuples are converted to the list >>> print (repr (obj) [[1, 2, 3], ('A', 'B', 'C'), {'4': 5, '6': 7}, 'def'] # Here it is just converted to a string

>>> Json. dumps ({'B': 4, 'A': 5, 'E': 6 })
'{"A": 5, "B": 4, "e": 6 }'
>>> Json. dumps ({'B': 4, 'A': 5, 'E': 6}, sort_keys = True)
'{"A": 5, "B": 4, "e": 6 }'
>>> A = json. dumps ({'B': 4, 'A': 5, 'E': 6}, sort_keys = True, indent = 5) # indent indicates that the indent is 5
>>> Print ()
{
"A": 5,
"B": 4,
"E": 6
}

During the Json encoding process, there will be a conversion from the Python data type to the Json type.

Python Json
Dict Object
List, tuple Array
Str String
Int, float Number
True True
False False
None Null
## decode>>> encoding_json'[[1, 2, 3], ["a", "b", "c"], {"4": 5, "6": 7}, "def"]'>>> decoding_json=json.loads(encoding_json)>>> print(decoding_json)[[1, 2, 3], ['a', 'b', 'c'], {'4': 5, '6': 7}, 'def']>>> type(decoding_json)<class 'list'>>>> print(decoding_json[2]['4'])5

The data type conversion from Json to Python is as follows:

JSON Python
Object Dict
Array List
String Unicode
Number Int, long
Ture True
False False
Null None

 

Pickle can process more complex data types. For example, the function. pickle module executes the binary protocol for python serialization and deserialization. Pickle is just a python

Serialized object, useful only for python.

Comparison with Json

1. JSON is a text serialization format, while pickle is a binary serialization format;

2. JSON is human-readable, while pickle is not;

3. JSOn is interoperable and widely used outside of the Python ecosystem, while pickle is Python-specific;

Common usage of Pickcle and Json: dumps/loads/dump/load

Pickcle. dump (obj, file. [protocol])

Serialize the object and write the result data stream to the file object. The protocol parameter is the serialization mode. The default value is 0, indicating serialization in the form of text.

The value of protocol can also be 1 or 2, indicating that the protocol is serialized in binary format.

Pickle. load (file)

Deserialization object: parses the data in the file into a python object.

Eg: serialization

# encodingimport pickledata = {    'a':[1,2,0,3],    'b':('string',u'unicode string'),    'c': {None,True,False}}with open('data.pickle','wb') as f:    # pickcle the 'data' dictionary using the higheset protocol available.    pickle.dump(data,f,pickle.HIGHEST_PROTOCOL)

Deserialization:

#! /Webapp/python/python3/bin/python3import picklewith open ('data. pickle ', 'rb') as f: data = pickle. load (f) print (data) for key in data: print (key, '--->', data [key]) # result {'A': [1, 2, 0, 3], 'B': ('string', 'unicode string'), 'C': {False, True, None} a ---> [1, 2, 0, 3] B ---> ('string', 'unicode string') c ---> {False, True, None}

 

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.