jsonclasses
jsonclasses copied to clipboard
key alias for jsonclasses
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')
Hi @ViktorSky, I guess we can.
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
Hi @ViktorSky, do you mean nested models?
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
"""
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?
Is there anyone reading?