2

I have defined 2 models in my flask-restplus app.

some_model = ns.model('SomeModel', {
    'a': fields.String,
    'b': fields.String,
    'c': fields.String
})

some_model_expanded = ns.inherit('SomeModelExpanded', some_model, {
    'd': fields.String,
    'e': fields.String,
})

Now when marshaling an API response with some_model_expanded, I got this in JSON format

{
    "d": "...",
    "e": "...",
    "a": "...",
    "b": "...",
    "c": "..."
}

Is it possible to reorder the fields like this?

{
    "a": "...",
    "b": "...",
    "c": "...",
    "d": "...",
    "e": "...",
}
user1285245
  • 423
  • 3
  • 9

2 Answers2

1

You will find your answer here. But in short:

Both Python dict (before Python 3.7) and JSON object are unordered collections.

There is workarounds to order them, but I dont think it s a good idea to rely on the order of items in a JSON object.

SivolcC
  • 3,258
  • 2
  • 14
  • 32
1

Yeah. You can use Ordered Dictionary while defining your model.

some_model = ns.model('SomeModel', 
    OrderedDict(
    'a': fields.String,
    'b': fields.String,
    'c': fields.String
    ))
pitt
  • 25
  • 2
  • 10