从json创建多个python类实例

时间:2016-10-31 03:47:23

标签: python json

我正在编写一些测试来评估休息服务 我的回答是

[ { "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 } ]

需要创建类的多个实例

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)

这工作正常....我需要知道有更短暂和甜蜜的方式吗?

2 个答案:

答案 0 :(得分:2)

你可以解压每个dict并将其作为TitleInfo的参数:

RecTitles = [TitleInfo(**x) for x in json.loads(response)]

以下是Python tutorial的解释:

  

以相同的方式,字典可以使用** - 运算符提供关键字参数:

>>> 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 !

答案 1 :(得分:1)

顺便说一句,您通常希望避免手动编码验证代码。签出API文档框架:swagger,RAML,API Blueprint。所有这些都有用于请求/响应验证的工具。

下一步是使用像dredd这样的测试框架。