marshalling dictionary with variable keys in flask restful /plus marshalling dictionary with variable keys in flask restful /plus flask flask

marshalling dictionary with variable keys in flask restful /plus


Sometimes you have your own custom formatting needs. You can subclass the fields.Raw class and implement the format function. This is especially useful when an attribute stores multiple pieces of information. e.g. a bit-field whose individual bits represent distinct values. You can use fields to multiplex a single attribute to multiple output values.

If you don’t know the name(s) of the field(s) you want to unmarshall, you can use Wildcard.

>>> from flask_restplus import fields, marshal>>> import json>>>>>> wild = fields.Wildcard(fields.String)>>> wildcard_fields = {'*': wild}>>> data = {'John': 12, 'bob': 42, 'Jane': '68'}>>> json.dumps(marshal(data, wildcard_fields))>>> '{"Jane": "68", "bob": "42", "John": "12"}'

The name you give to your Wildcard acts as a real glob as shown below.

>>> from flask_restplus import fields, marshal>>> import json>>>>>> wild = fields.Wildcard(fields.String)>>> wildcard_fields = {'j*': wild}>>> data = {'John': 12, 'bob': 42, 'Jane': '68'}>>> json.dumps(marshal(data, wildcard_fields))>>> '{"Jane": "68", "John": "12"}'

NoteIt is important you define your Wildcard outside your model (ie. you cannot use it like this: res_fields = {'': fields.Wildcard(fields.String)})* because it has to be stateful to keep a track of what fields it has already treated.