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_D
Solution 1:
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:
>>>defparrot(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 !
Solution 2:
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.
Post a Comment for "Creating Multiple Python Class Instance From Json"