No questions is Stupid No questions is Stupid - 1 month ago 4
Python Question

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?

Answer

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

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