jsonclasses icon indicating copy to clipboard operation
jsonclasses copied to clipboard

key alias for jsonclasses

Open ViktorSky opened this issue 1 year ago • 6 comments

Is it possible to get the value from aliases? this happens because the key value is too long to call the attributes

eg: here api returns something with repetitive or long text

data = {
    'sticker': {
        'stickerCollectionSummary': {
            'bannerUrl': str,
            'collectionId': str,
            # ...
        },
        'stickerId': str,
        # ...
    },
    # ...
}

and making the jsonclass of this is tedious and repetitive with the name

@jsonclass
class StickerCollectionSummary:
    bannerUrl: str
    collectionId: str
    # ...

@jsonclass
class Sticker:
    stickerCollectionSummary: StickerCollectionSummary
    stickerId: str
    # ...
sticker: Sticker = ... # get the object
# for get banner
sticker.stickerCollectionSummary.bannerUrl #too long
# for get collectionId
sticker.stickerCollectionSummary.collectionId # too long
# for get sticker id
sticker.stickerId # repetitive

If suggestions are accepted, I would ask that a method be added to get the key from the dict, to use the value in an alias as shown below.

# In this case, I decided to assume that there is a method fkey
# that, when starting the class, assigns the value from what is obtained from the key
# info: fkey is 'fetch key' or 'from key'

@jsonclass
class StickerCollectionSummary:
    bannerUrl: str
    id: str = types.str.fkey('collectionId')

@jsonclass
class Sticker:
    collection: StickerCollectionSummary = types.fkey('stickerCollectionSummary')
    id: str = types.str.fkey('stickerId')

ViktorSky avatar Jun 12 '23 03:06 ViktorSky

Hi @ViktorSky, I guess we can.

victorteokw avatar Jun 19 '23 06:06 victorteokw

Hi @ViktorSky, I guess we can.

How is it done? I have been reading the documentation but I have only found the references with ´linkedBy/linkedTo´, I have also read the source code, but it is a bit confusing to handle the modifiers

ViktorSky avatar Jun 22 '23 15:06 ViktorSky

Hi @ViktorSky, do you mean nested models?

victorteokw avatar Jun 25 '23 01:06 victorteokw

Hi @ViktorSky, do you mean nested models?

No, I meant to specify the key for the field.

@jsonclass
class User:
    name: str = types.str.alias('userName')
    type: int = types.int.alias('userType')

data = {
    'userName': 'John',
    'userType': 0
}

user = User(**data)
print(user)
"""
User(userName='John')
"""
print(user.name)
"""
John
"""


ViktorSky avatar Jun 27 '23 01:06 ViktorSky

Hi @ViktorSky, do you mean nested models?

https://github.com/fillmula/jsonclasses/issues/40#issuecomment-1608578998 Is it possible to use a field from a key alias?

ViktorSky avatar Nov 02 '23 02:11 ViktorSky

Is there anyone reading?

ViktorSky avatar Aug 13 '24 20:08 ViktorSky