1234
1234

Reputation: 241

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 } ]

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

what I have done is

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?

Upvotes: 0

Views: 206

Answers (2)

niemmi
niemmi

Reputation: 17263

You could just unpack each dict and give that as an argument to TitleInfo:

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

Here's the explanation from Python tutorial:

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 !

Upvotes: 2

rmharrison
rmharrison

Reputation: 5318

As an aside, you generally want to avoid hand-coding validation code. Checkout an API documentation framework: swagger, RAML, API Blueprint. All of them have tooling for request/response validation.

The next step would be to use a testing framework like dredd.

Upvotes: 1

Related Questions