Python's JSON encoding

Source: Internet
Author: User
Tags serialization python list

One, Jsonjson:javascript object Notation (JavaScript object notation) JSON is the syntax for storing and exchanging textual information 1, JSON Lightweight: Syntax rules JSON syntax is a subset of JavaScript object notation syntax. (1) data in name/value pairs (2) data is separated by commas (3) A curly brace represents an object (4) [] array, can hold multiple objects (5) string using double quotation marks   Two, Python type and JSON type conversion 1, the Python data, Convert to JSON format json.dumps (data,sort_keys=true,indent=4,separators= (', ', ': '), Skipkeys=true,ensure_ascii=false) Sort_ The keys default is False. Whether to sort by dictionary (A to Z) output: True (sorted by dictionary) indent: Each value is displayed in front of the empty 4-separators: Using the established character substitution, the function of the parameter is to remove the comma "," and the semicolon ":" After the space Skipkeys: Ignore the wrong data ensure_ascii: The default is true: the display outside the character is \u4e2d\u56fd 2, JSON decoding: Convert the JSON format into Python format json.loads () The JSON object type-----The array type of Python's dict type json------python's list type  import jsondata = [{' A ': ' A ', ' B ':(2,4), ' C ': 3.0 , ' d ': None, ' e ': true}]print Datadatajson = Json.dumps (' data,sort_keys=true,separators= (', ', ': '), indent=4,skipkeys= True) Print Datajson print json.loads (Datajson)  3, encoding process, list and tuple in Python are converted to JSON arrays, and after decoding, The JSON array is eventually transformed into a python list, whether it's a list or a tuple.   Serialization and deserialization 1. Convert the Python class object to JSON format: Use the default parameter in the dumps () function Import Jsonclass Employee (objECT):d EF __init__ (self,name,age,sex,tel): Self.name = Nameself.age = Ageself.sex = Sexself.tel = tel# defines the serialization function inside the class Def ObjJ Son: return {' name ': Self.name, ' age ': self.age, ' sex ': self.sex, ' tel ': self.tel} e1 = Employee (' Andy ', ' 24 ', ' Male ', ' 131xxxxxxxx ') print json.dumps (E1,default=e1.objjson)   #另一个更简单的方法e1 =employee (' Andy ', ' a ', ' Male ', ' 131xxxxxxxx ') # print json.dumps (e1,default=e1.objjson) print json.dumps (e1.__dict__) typically a class and its instances will have a __dict__ Property (unless the __slots__ attribute is added to the class), it is a dict type that stores the properties that are valid in a class or class instance.  2, JSON deserializes a class object JSON string into an instance of a class object or class, using the Object_hook parameter in the loads () method. Json.loads (Data,object_hook=jsontoclass)  class Employee (object):d EF __init__ (Self,name,age,sex,tel): Self.name = Nameself.age = Ageself.sex = Sexself.tel = Teldef Objjson (self,obj_instance): return {' name ': obj_ Instance.name, ' age ': obj_instance.age, ' sex ': obj_instance.sex, ' tel ': obj_instance.tel} e1 = Employee (' Andy ', ' (' Male ', ' 131xxxxxxxx ') print json.dumps (e1.__dict__) #fucn (E1) print E1.__dict__ def Jsontoclass (DICTVAR): Return Employee (dictvar[' name '],dictvar[' age '],dictvar[' sex '],dictvar[' tel ']) Jsondate = {"Age": "+", "tel": " 131xxxxxxxx "," name ":" Andy "," Sex ":" male "}e = Json.loads (jsondate,object_hook=jsontoclass) print Eprint e.name  Four , Python type                 JSON string type dict                             ObjectList, tuple                    ARRAYSTR, Unicode               Stringint, long, float   &NBS P        numbertrue                          truefalse                        falsenone                        null

Python JSON encoding

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.