Network Security Internet Technology Development Database Servers Mobile Phone Android Software Apple Software Computer Software News IT Information

In addition to Weibo, there is also WeChat

Please pay attention

WeChat public account

Shulou

What are the class object methods for converting JSON data format to Python

2025-01-18 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >

Share

Shulou(Shulou.com)06/02 Report--

This article mainly talks about "what are the class object methods for converting JSON data format to Python", interested friends may wish to have a look. The method introduced in this paper is simple, fast and practical. Next let the editor to take you to learn "what are the class object methods for converting JSON data format to Python"?

Sometimes we have this requirement to convert a JSON string into an instance of a specific Python class, for example, you receive a JSON string as follows:

{"Name": "Tom", "Sex": "Male", "BloodType": "A", "Hobbies": ["basketball", "football"]}

I need to convert this to a concrete instance of the Person class and operate in the form of an object. There are many implementations in Java, such as Gson or FastJosn. As shown in the following code (not all of the code here, the value identifies the most important part):

Import com.alibaba.fastjson.JSONObject

Import com.example.demo.entity.Product

String a = "{\" gmtCreate\ ": 1559009853000,\" dataFormat\ ": 1,\" deviceCount\ ": 1,\" nodeType\ ": 0,\" productKey\ ":\" a1U85pSQrAz\ ",\" productName\ ":\" thermometer\ "

/ / the JSON string is deserialized into a Product object

Product product = JSONObject.parseObject (a, Product.class)

The above requirements generally occur when the JSON string is passed in the previous paragraph or when other systems communicate with RPC, and the JSON string is also sent to the receiver, which needs to be deserialized into an object for processing, and there is a JSONArray.parseArray method in Fastjson that can be converted into an object list. But there is nothing as convenient in Python as in Java.

I have also seen some from online forums, but many of them are effective but troublesome to use, so I would like to talk about my ideas here.

Method 1: implement through josn.loads

#! / usr/bin/env python

#-*-coding: utf-8-*-

Import sys

Import json

Class Person:

Def _ _ init__ (self, data=None):

Self._name = "1"

Self._sex = ""

Self._blood_type = "O"

Self._hobbies = []

Self._date_of_birth = "1900-1-1"

If data:

Self.__dict__ = data

# get and set the value of the instance variable through the property. If not, you can only do it through the set or get method.

@ property

Def date_of_brith (self):

Return self._date_of_birth

@ date_of_brith.setter

Def date_of_brith (self, date_of_brith):

Self._date_of_birth = date_of_brith

Def main ():

Try:

Str1 ='{"name": "Tom", "sex": "male", "blood_type": "A", "hobbies": ["basketball", "football"]}'

Person1 = json.loads (str1, object_hook=Person)

Print (isinstance (person1, Person))

# you will find that there is no such thing as date_of_brith here

Print (person1.__dict__)

# getting the date_of_brith attribute value reported an error, because the JSON string does not contain this key, but the instance variable in the class has this, normally you should be able to get the default value, but because

# replaced _ _ dict__, so it's gone, because _ _ dict__ is already a dictionary form of instance variables, and you can't find the original if you replace nature.

# print (person.date_of_brith)

# Let's instantiate an object in a normal way

Person2 = Person ()

Print (person2.__dict__)

Print (person2.date_of_brith)

Except Exception as err:

Print (err)

If _ name__ = = "_ _ main__":

Try:

Main ()

Finally:

Sys.exit ()

Object_hook means that the default json.loads () returns dict, and you can use object_hook to make it return values of other types. The principle here is that the JSON string you pass in is passed to the method or class specified by object_hook (if it is a class, the _ _ init__ method is executed, which is actually instantiation). At this time, we assign a value to self.dict__ in the class's _ _ value method. In fact, this is tantamount to replacing the instance variables of the Person class. Unless the key of your JSON string is the same as the name and number of instance variables, you cannot get the value passed through the JSON string through the instance variable name you define in the class.

So as you can see from the above, this process is not a process of assigning values to instance variables, but a process of substitution, unlike JAVA, where Python is a dynamic language. If you use a single underscore in the program to identify the variable as private (only canonical rather than truly private) then the key of the JSON string you pass also needs to be underlined so that you can get it through the instance method. Since it is not realistic to add extra underscores, is there any other way? Look at mode 2

Mode 2: through reflection mechanism to achieve

Take a look at the definition of the class first.

#! / usr/bin/env python

#-*-coding: utf-8-*-

Class Person:

Def _ init__ (self):

Self._name = "1"

Self._sex = ""

Self._blood_type = "O"

Self._hobbies = []

Self._date_of_birth = "1900-1-1"

Def _ str__ (self):

""

Output the class name of the instance instead of an address

: return: the class name of the instance

""

Return self.__class__.__name__

# when a method adds this decorator, the properties in hasattr () are written as the name of the method, not the name of the instance variable.

# if you do not add this decorator, then the attribute name in hasattr () should be the same as the name of the instance variable

@ property

Def Name (self):

Return self._name

@ Name.setter

Def Name (self, name):

Self._name = name

@ property

Def Sex (self):

Return self._sex

@ Sex.setter

Def Sex (self, sex):

Self._sex = sex

@ property

Def BloodType (self):

Return self._blood_type

@ BloodType.setter

Def BloodType (self, blood_type):

Self._blood_type = blood_type

@ property

Def Hobbies (self):

Return self._hobbies

@ Hobbies.setter

Def Hobbies (self, hobbies):

Self._hobbies = hobbies

@ property

Def date_of_brith (self):

Return self._date_of_birth

@ date_of_brith.setter

Def date_of_brith (self, date_of_brith):

Self._date_of_birth = date_of_brith

Let's take a look at the conversion method.

#! / usr/bin/env python

#-*-coding: utf-8-*-

Import sys

Import json

Import importlib

Def get_instance (str_stream, class_full_path=None):

The cost of artificial abortion in Zhengzhou http://www.zzzzyy120.com/

: param str_stream: the string form of json'{"Name": "Tom", "Sex": "Male", "BloodType": "A"}'

: param class_full_path: package.module.class

: return:

""

Try:

Json_obj = json.loads (str_stream)

Except Exception as err:

Print ("the string entered does not conform to the JSON format, please check.")

Return None

If class_full_path is None:

Return json_obj

Else:

Try:

# get the module path

Module_path = "." .join (class_full_path.split (".") [0VRAP1])

# get the class name

Class_name = class_full_path.split (".") [- 1]

# load the module through the module name

CC = importlib.import_module (module_path)

# determine whether there is an attribute represented by class_name

If hasattr (CC, class_name):

# get attributes in module

Temp_obj = getattr (CC, class_name)

# instantiate object

Obj = temp_obj ()

For key in json_obj.keys ():

Obj.__setattr__ (key, json_ OBJ [key])

Return obj

Else:

Pass

Except Exception as err:

Print (err)

Return None

Def main ():

Try:

Str1 ='{"Name": "Tom", "Sex": "Male", "BloodType": "A", "Hobbies": ["basketball", "football"]}'

Person1 = get_instance (str1, class_full_path= "AAA.Classes.Person")

# View Type

Print (type (person1))

# View Properties

Print (person1.__dict__)

# View specified properties

Print (person1.Name)

Except Exception as err:

Print (err)

If _ name__ = = "_ _ main__":

Try:

Main ()

Finally:

Sys.exit ()

Import () has two parameters, the first is the class, and the second is fromlist. If fromlist is not written, only the AAA package will be imported. If fromlist has a value, it will be imported into the Classes module under AAA cc = import ("AAA.Classes", fromlist=True). Do not write fromlist is equivalent to import AAA, if it is equivalent to from AAA import Classes programming, if you use dynamic loading, it is recommended to use importlib.import_module () instead of _ _ import__ ().

Get the effect.

As you can see, this operation assigns values to the instance variables instead of replacing them as before, and retains the private specification of the instance variables in the class. However, it is important to note that the key name in the JSON string should be the same as the property name defined in the class, that is, the key name should be the same as the method decorated by @ property in the class. We can also see that this usage also means default JSONObject.parseObject.

At this point, I believe that we have a deeper understanding of the "JSON data format conversion to Python class object methods", might as well to the actual operation of it! Here is the website, more related content can enter the relevant channels to inquire, follow us, continue to learn!

Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.

Views: 0

*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.

Share To

Development

Wechat

© 2024 shulou.com SLNews company. All rights reserved.

12
Report