简体   繁体   中英

Failing to parse complex JSON using Python and Marshmallow

I am using Marshmallow to create a mapper for a JSON file. Following are the details:

My JSON File:

{
    "version": "3.0",
    "name": "A1",
    "request": {
        "startdate": "26022022",
        "enddate": "26022022",
        "records": 1000
    },
    "ranking": {
        "90": {
            "name": "N1",
            "class1": "C1"
        },
        "98": {
            "name": "N2",
            "class1": "C2"
        },
        "86": {
            "name": "N3",
            "class1": "C3"
        }
    }
}

My mapper class:

class RequestMapper(Schema):
    startdate = fields.String()
    enddate = fields.String()
    records = fields.Int()

class Ranking(Schema):
    name = fields.String()
    class1 = fields.String()

class RankingMapper(Schema):
    rank = fields.Nested(Ranking(), dataKey = fields.Int)

class SampleSchema(Schema):
    name = fields.Str()
    request = fields.Nested(RequestMapper())
    ranking = fields.Nested(RankingMapper())

Code to call Mapper:

        print("\n\nOutput using mapper")
        pprint(mapper.SampleSchema().dump(data), indent=3)
        print("\n\n")

Following is the output:

Output using mapper
{  'name': 'A1',
   'ranking': {},
   'request': {'enddate': '26022022', 'records': 1000, 'startdate': '26022022'}}

I am not getting any data for ranking as datakey [90, 98, 86...] are dynamic and am not sure how to create mapper for dynamic keys please.

Any inputs will be helpful.

Thank you

When nesting schemas, pass the class NAME, not a class instance:


class RankingMapper(Schema):
    rank = fields.Nested(Ranking, dataKey = fields.Int)

class SampleSchema(Schema):
    name = fields.Str()
    request = fields.Nested(RequestMapper)
    ranking = fields.Nested(RankingMapper)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM