JSON and pickle of Python serialization

Source: Internet
Author: User
Tags string back

1. JSON INTRODUCTION

JSON (JavaScript Object Notation) is a lightweight data interchange format. Easy for people to read and Write. It is also easy for machine parsing and Generation. It is based on JavaScript programming Language, standard ECMA-262 a subset of 3rd Edition-december 1999. JSON takes a completely language-independent text format, but also uses a similar idiom to the C language family (c, C + +, c #, Java, JavaScript, Perl, python, etc.). These features make JSON an ideal data exchange Language.

The JSON module can be used to encode JSON data in Python3, which contains two functions:

    1. Json.dumps (): encode the data
    2. Json.loads (): Decoding the data
Json.dumps and Json.loads instances

The following example demonstrates the conversion of a PYTHON data structure to a JSON

1 #!/usr/bin/env python2 #_*_ coding:utf-8 _*_3 #Author:enzhi.wang4 ImportJSON5 #convert the underlying data type of Python into a string6DIC = {"K1":"v1","K2":"v2"}7 Print("python raw Data:", repr (dic), type (dic )8result = Json.dumps (dic)#converting a dictionary type to a string type9 Print("JSON object:", Result,type (result))

Execute the above code to output the Result:

C:\Python3.5\python.exe c:/users/root/pycharmprojects/s14/day4/JSON Serialization. Pypython Raw Data: {'K1':'v1','K2':'v2'} <class 'Dict'>JSON object: {"K1":"v1","K2":"v2"} <class 'Str'>

The result of the output shows that the simple type is very similar by encoding followed by its original repr () Output.

next, we can convert a json-encoded string back to a python data structure:

1 #!/usr/bin/env python2 #_*_ coding:utf-8 _*_3 #Author:enzhi.wang4 ImportJSON5 #convert the underlying data type of Python into a string6DIC = {"K1":"v1","K2":"v2"}7 Print("python raw Data:", repr (dic), type (dic )8result = Json.dumps (dic)#converting a dictionary type to a string type9 Print("JSON object:", Result,type (result))Ten  one #To convert a Python string type to a python base data type aresult =json.loads (result) - Print("result[' K1 ']:", result['K1']) - Print("result[' K2 ']:", result['K2'])

Execute the above code to output the Result:

C:\Python3.5\python.exe c:/users/root/pycharmprojects/s14/day4/JSON Serialization. Pypython Raw Data: {'K1':'v1','K2':'v2'} <class 'Dict'>JSON object: {"K1":"v1","K2":"v2"} <class 'Str'>result['K1']: v1result['K2']: v2

If you are dealing with files instead of strings, you can use json.dump () and json.load () to encode and decode JSON Data. For example:

1data = {2     "name":"Wangenzhi",3     " age": 25,4     "Job":"Ops"5 }6 #Writing JSON data7With open ('Db.json','W') as F:8 json.dump (data,f)9 Ten #Reading JSON data oneWith open ('Db.json','R') as F: ares =json.load (f) -     Print(res,type (RES))

For more information, please refer to: https://docs.python.org/3/library/json.html

2, Pickle Introduction

The data format used by the Pickle module is python-specific and is not backwards compatible with different versions and cannot be recognized by other Languages. To interact with other languages, you can use the built-in JSON package with the Pickle module you can save Python objects directly to a file without having to convert them to a string, or write them into a binary file without the underlying file access Operation. The Pickle module creates a python-language-specific binary format, and you basically don't have to consider any file details, it will help you cleanly complete the read and write exclusive operation, only need a valid file Handle.

The Python3 can be used to encode and decode the data using the pickle Module. It consists of two functions:

    1. Pickle.dumps ()
    2. Pickle.loads ()
Pickle.dumps and Pickle.loads instances
1 #!/usr/bin/env python2 #_*_ coding:utf-8 _*_3 #Author:enzhi.wang4 ImportPickle5 6data = {7     "name":"Wangenzhi",8     " age": 25,9     "Job":"Ops"Ten } one  a Print("Original Python object:", repr (data)) -R =pickle.dumps (data) - Print("Pickle the converted Object:", R) theres =pickle.loads (r) - Print("res[' name ']:", res['name']) - Print("res[' Age ']:", res[' age']) - Print("res[' Job ']:", res['Job'])

Execute the above code to output the Result:

C:\Python3.5\python.exe c:/users/root/pycharmprojects/s14/day4/Pickle serialization. py original python object: {'name':'Wangenzhi','Job':'Ops',' age': 25}pickle converted Object: B'\x80\x03}q\x00 (x\x04\x00\x00\x00nameq\x01x\t\x00\x00\x00wangenzhiq\x02x\x03\x00\x00\x00jobq\x03x\x03\x00\ X00\x00opsq\x04x\x03\x00\x00\x00ageq\x05k\x19u.'res['name']: wangenzhires[' age']: 25res['Job']: Ops

If you are dealing with files instead of strings, you can use pickle.dump () and pickle.load () to encode and decode JSON Data. For example:

1 ImportPickle2 3data = {4     "name":"Wangenzhi",5     " age": 25,6     "Job":"Ops"7 }8 #write data to be written in WB format9Pickle.dump (data,open ('DB','WB'))Ten #read data, to be read in RB format onef = open ('DB','RB') ares =pickle.load (f) - Print(res)

Execute the above code to output the Result:

C:\Python3.5\python.exe c:/users/root/pycharmprojects/s14/day4/Pickle serialization. py{'job  'ops''name' 'wangenzhi'  'age': 25}
Summary

JSON: for cross-language, python-only for Python basic data types

Pickle: applies only to Python,pickle serialization for all data types in Python

JSON and pickle of Python serialization

Related Article

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.