currently, I met a problem with marshal_with decorator. I want to marshal dict data with dynamic key, it looks like below
{ "nickname": "Jack",
"sex": "male",
"matched_people": {"Eric": 5, "John": 3},
...
}
the value of "matched_people" is a dynamic generated dict, how can I marshal_with in this case?
I tried the following:
user_fields = {
"nickname": fields.String,
"sex": fields.String,
"matched_people": fields.Nested({}), # also tried with fields.Raw
....
}
It doesn't work, so how to define the fields?
Thanks
fields.Raw is what I've used, which works as long as the types in the raw dict are all json serializable.
Hi Joshfriend,
Thanks for your feedback.
I've already tried with fields.Raw like:
user_fields = {
"matched_people": fields.Raw,
....
}
But it didn't work, am I wrong somewhere?
Thanks
When you say "it doesn't work", does that mean an exception is being thrown? If so, what is it? Or does the data come back in the response incomplete or garbled? Please give more information about what is going wrong.
Hi Joshfriend,
I tried again and it works, the error is caused by other reasons.
Thanks
For anyone reading this I would advise making the data structures more predictable in this case rather than using fields.Raw. So for example rather than:
"matched_people": {"Eric": 5, "John": 3},
I would advise changing it to:
"matched_people": [
{ "name" : "Eric", "value": 5 },
{ "name" : "John", "value": 3 }
]
@HamadaFMahdi unfortunately that won't often work for cases when the response structure has to be efficiently indexed on some of the result fields. For example, if you must get value for the response item with name equal to "Eric", if you don't use dynamic fields, then the client will have to do a linear search over all the response items and cannot index directly on "Eric" like it is a hash table key. Sometimes this is a critical aspect of the response requirements.
Most helpful comment
fields.Rawis what I've used, which works as long as the types in the raw dict are all json serializable.