从json创建多个python类实例 [英] creating multiple python class instance from json
问题描述
我正在编写一些测试以评估休息服务 我的回应是
I am writing some tests to evaluate a rest service my response is
[
{
"Title_Id": 1,
"Title": "Mr",
"TitleDescription": "Mr",
"TitleGender": "Male",
"Update_Date": "2012-07-21T18:43:04"
},
{
"Title_Id": 2,
"Title": "Mrs",
"TitleDescription": "Mrs",
"TitleGender": "Female",
"Update_Date": "2012-07-21T18:42:59"
},
{
"Title_Id": 3,
"Title": "Sir",
"TitleDescription": "Sir",
"TitleGender": "Male",
"Update_Date": null
}
]
[
{
"Title_Id": 1,
"Title": "Mr",
"TitleDescription": "Mr",
"TitleGender": "Male",
"Update_Date": "2012-07-21T18:43:04"
},
{
"Title_Id": 2,
"Title": "Mrs",
"TitleDescription": "Mrs",
"TitleGender": "Female",
"Update_Date": "2012-07-21T18:42:59"
},
{
"Title_Id": 3,
"Title": "Sir",
"TitleDescription": "Sir",
"TitleGender": "Male",
"Update_Date": null
}
]
,并且需要创建该类的多个实例
and need to create multiple instance of the class
class TitleInfo:
def __init__(self, Title_Id, Title, TitleDescription, TitleGender, Update_Date ):
self.Title_Id = Title_Id
self.Title = Title
self.TitleDescription = TitleDescription
self.TitleGender = TitleGender
self.Update_Date = Update_Date
我所做的是
def GetTitle(self):
try:
response = *#......"The string shown above"*
if isinstance(response, str) :
Records = json.loads(response)
RecTitles = []
for num in range(0, len(Records)):
RecTitle =TitleInfo(Records[num]['Title_Id'],Records[num]['Title'],Records[num]['TitleDescription'],Records[num]['TitleGender'],Records[num]['Update_Date'])
RecTitles.append(RecTitle)
这很好用....我需要知道还有其他更简短的方法吗?
This is working fine ....I need to know is there more short and sweet way to do that?
推荐答案
您可以解压缩每个dict
并将其作为TitleInfo
的参数:
You could just unpack each dict
and give that as an argument to TitleInfo
:
RecTitles = [TitleInfo(**x) for x in json.loads(response)]
以下是 Python教程中的说明:
以相同的方式,词典可以使用**运算符传递关键字参数:
In the same fashion, dictionaries can deliver keyword arguments with the **-operator:
>>> def parrot(voltage, state='a stiff', action='voom'):
... print("-- This parrot wouldn't", action, end=' ')
... print("if you put", voltage, "volts through it.", end=' ')
... print("E's", state, "!")
...
>>> d = {"voltage": "four million", "state": "bleedin' demised", "action": "VOOM"}
>>> parrot(**d)
-- This parrot wouldn't VOOM if you put four million volts through it. E's bleedin' demised !
这篇关于从json创建多个python类实例的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!