Skip to content

Marshaled nested wildcard field with ordered=True doesn't preserve dictionary key order. #304

@KungFuLucky7

Description

@KungFuLucky7

Marshaled nested wildcard field with ordered=True doesn't preserve dictionary key order.

Code

from flask_restx import fields, marshal

wild = fields.Wildcard(fields.String)
wildcard_fields = {'*': wild}
value = {'John': 12, 'bob': 42, 'Jane': '68'}
data = marshal(
      value, wildcard_fields, ordered=True
  )
print(data)

>> OrderedDict([('Jane', '68'), ('bob', '42'), ('John', '12')])

Repro Steps (if applicable)

  1. See above sample code

Expected Behavior

The marshaled dictionary's keys have the same order.

OrderedDict([('John', '12'), ('bob', '42'), ('Jane', '68')])

Actual Behavior

The marshaled dictionary's keys order is not preserved.

Environment

  • Python 3.9
  • Flask version 1.1.2
  • Flask-RESTX version 0.3.0
  • Other installed Flask extensions

Additional Context

Currently I'm sorting the dictionary keys with a custom field to solve my problem:

class CustomNested(fields.Nested):
    def output(self, key, obj, ordered=True, **kwargs):
        data = super().output(key, obj, ordered=ordered, **kwargs)
        return OrderedDict(sorted(data.items()))

Metadata

Metadata

Assignees

No one assigned

    Labels

    bugSomething isn't working

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions