Home > front end >  How to create an automatic mapping of possible JSON data options to be collected?
How to create an automatic mapping of possible JSON data options to be collected?

Time:02-08

I've never heard of or found an option for what I'm looking for, but maybe someone knows a way:

To collect the data from a JSON I need to map manually it like this:

events = response['events']
for event in events:
    tournament_name = event['tournament']['name']
    tournament_slug = event['tournament']['slug']
    tournament_category_name = event['tournament']['category']['name']
    tournament_category_slug = event['tournament']['category']['slug']
    tournament_category_sport_name = event['tournament']['category']['sport']['name']
    tournament_category_sport_slug = event['tournament']['category']['sport']['slug']
    tournament_category_sport_id = event['tournament']['category']['sport']['id']

The complete model is this:

{
    "events": [
      {
        "tournament": {
          "name": "Serie A",
          "slug": "serie-a",
          "category": {
            "name": "Italy",
            "slug": "italy",
            "sport": {
              "name": "Football",
              "slug": "football",
              "id": 1
            },
            "id": 31,
            "flag": "italy",
            "alpha2": "IT"
          },
          "uniqueTournament": {
            "name": "Serie A",
            "slug": "serie-a",
            "category": {
              "name": "Italy",
              "slug": "italy",
              "sport": {
                "name": "Football",
                "slug": "football",
                "id": 1
              },
              "id": 31,
              "flag": "italy",
              "alpha2": "IT"
            },
            "userCount": 586563,
            "id": 23,
            "hasEventPlayerStatistics": true
          },
          "priority": 254,
          "id": 33
        },
        "roundInfo": {
          "round": 24
        },
        "customId": "Kdbsfeb",
        "status": {
          "code": 7,
          "description": "2nd half",
          "type": "inprogress"
        },
        "winnerCode": 0,
        "homeTeam": {
          "name": "Bologna",
          "slug": "bologna",
          "shortName": "Bologna",
          "gender": "M",
          "userCount": 39429,
          "nameCode": "BOL",
          "national": false,
          "type": 0,
          "id": 2685,
          "subTeams": [
            
          ],
          "teamColors": {
            "primary": "#003366",
            "secondary": "#cc0000",
            "text": "#cc0000"
          }
        },
        "awayTeam": {
          "name": "Empoli",
          "slug": "empoli",
          "shortName": "Empoli",
          "gender": "M",
          "userCount": 31469,
          "nameCode": "EMP",
          "national": false,
          "type": 0,
          "id": 2705,
          "subTeams": [
            
          ],
          "teamColors": {
            "primary": "#0d5696",
            "secondary": "#ffffff",
            "text": "#ffffff"
          }
        },
        "homeScore": {
          "current": 0,
          "display": 0,
          "period1": 0
        },
        "awayScore": {
          "current": 0,
          "display": 0,
          "period1": 0
        },
        "coverage": 1,
        "time": {
          "initial": 2700,
          "max": 5400,
          "extra": 540,
          "currentPeriodStartTimestamp": 1644159735
        },
        "changes": {
          "changes": [
            "status.code",
            "status.description",
            "time.currentPeriodStart"
          ],
          "changeTimestamp": 1644159743
        },
        "hasGlobalHighlights": false,
        "hasEventPlayerStatistics": true,
        "hasEventPlayerHeatMap": true,
        "id": 9645399,
        "statusTime": {
          "prefix": "",
          "initial": 2700,
          "max": 5400,
          "timestamp": 1644159735,
          "extra": 540
        },
        "startTimestamp": 1644156000,
        "slug": "empoli-bologna",
        "lastPeriod": "period2",
        "finalResultOnly": false
      }
    ]
  }

In my example I am collecting 7 values.
But there are 83 possible values to be collected.

In case I want to get all the values options that exist in this JSON, is there any way to make this map sequence automatically to print so I can copy it to the code?

Because manually it takes too long to do and it's very tiring.

And the results of texts like print() in terminal would be something like:

tournament_name = event['tournament']['name']
tournament_slug = event['tournament']['slug']
...
...
...
And so on until delivering the 83 object paths with values to collect...

Then I could copy all the prints and paste into my Python file to retrieve the values or any other way to make the work easier.

CodePudding user response:

If the elements in the events arrays are the same, this code works without errors.

def get_prints(recode: dict):
    for key in recode.keys():
        if type(recode[key]) == dict:
            for sub_print in get_prints(recode[key]):
                yield [key]   sub_print
        else:
            yield [key]



class Automater:
    def __init__(self,name: str):
        """
        Params:
            name: name of json
        """
        self.name = name

    def get_print(self,*args):
        """
        Params:
            *args: keys json
        """
        return '_'.join(args)   ' = '   self.name   ''.join([f"['{arg}']" for arg in args])

For example, this code:

dicts = {
    'tournament':{
        'name':"any name",
        'slug':'somthing else',
        'sport':{
            'name':'sport',
            'anotherdict':{
                'yes':True
            }
        }
    }
}
list_names = get_prints(dicts)
for name in list_names:
    print(auto.get_print(*name))

Gives this output:

tournament_name = event['tournament']['name']
tournament_slug = event['tournament']['slug']
tournament_sport_name = event['tournament']['sport']['name']
tournament_sport_anotherdict_yes = event['tournament']['sport']['anotherdict']['yes']
  •  Tags:  
  • Related