TransWikia.com

Deserialize 3rd party json to python class object

Stack Overflow Asked on December 16, 2021

I have a json from 3rd party which looks like this:

{
  "id": "5fc2aa38-cd0a-11ea-87d0-0242ac130003",
  "name": "Boca",
  "div": 9,
  "players": [
    {
      "id": "908c592a-cd0a-11ea-87d0-0242ac130003",
      "name": "Tevez",
      "goals": {
        "league": 152,
        "cup": 35,
        "international": 77
      },
      "number": 10
    },
    {
      "id": "99dcdd60-cd0a-11ea-87d0-0242ac130003",
      "name": "Lopez",
      "goals": {
        "league": 22,
        "cup": 3,
        "international": 4
      },
      "number": 20
    }
  ]
}

I need to deserialize into the python class ‘Team’ that contains the ‘Player’ and ‘Goal’ classes:

class Team(object):
    def __init__(self, id, name, div, players):
        self.id = id
        self.name = name
        self.div = div
        self.players = players

class Player(object):
    def __init__(self, id, name, goals, numbers):
        self.id = id
        self.name = name
        self.goals = goals
        self.numbers = numbers
        
class Goal(object):
    def __init__(self, league, cup, international):
        self.league = league
        self.cup = cup
        self.international = international

I have no problem to use type hints in the classes definition.
The best thing I came up with is to take this json, transform it to dictionary with json.dumps() and then add keys to dictionary with the name of the class (like metadata):

{
  "__team__": true,
  "id": "5fc2aa38-cd0a-11ea-87d0-0242ac130003",
  "name": "Boca",
  "div": 9,
  "players": [
    {
      "__player__": true
      "id": "908c592a-cd0a-11ea-87d0-0242ac130003",
      "name": "Tevez",
      "goals": {
        "__goal__": true,
        "league": 152,
        "cup": 35,
        "international": 77
      },
      "number": 10
    },
    {
      "__player__": true
      "id": "99dcdd60-cd0a-11ea-87d0-0242ac130003",
      "name": "Lopez",
      "goals": {
        "__goal__": true,
        "league": 22,
        "cup": 3,
        "international": 4
      },
      "number": 20
    }
  ]
}

Then, I want to use json.dump() to have the json with the ‘metadata’, and then use object_hook of json.loads() like in the following example
https://docs.python.org/3/library/json.html

>>> import json
>>> def as_complex(dct):
...     if '__complex__' in dct:
...         return complex(dct['real'], dct['imag'])
...     return dct
...
>>> json.loads('{"__complex__": true, "real": 1, "imag": 2}',
...     object_hook=as_complex)
(1+2j)
>>> import decimal
>>> json.loads('1.1', parse_float=decimal.Decimal)
Decimal('1.1')

It seems to be so complicated but what are the alternatives?

Add your own answers!

Ask a Question

Get help from others!

© 2024 TransWikia.com. All rights reserved. Sites we Love: PCI Database, UKBizDB, Menu Kuliner, Sharing RPP