Skip to content

Custom map key sort functions #384

Open
@zachelrath

Description

@zachelrath

Currently, when SortMapKeys is set to true in Config, map keys are sorted using a standard alphanumeric sort. It should be possible to specify a custom map key sorting function to use, in order to prioritize certain map keys over others.

Example: Standard SortMapKeys behavior:

cfg := jsoniter.Config{
   SortMapKeys: true,
}.Froze()

m := map[string]int{
   "beta": 2,
   "alpha": 1,
}
output, _ := cfg.MarshalToString(m)

==> {"alpha":1,"beta":2}

Example: custom SortMapKeys behavior:

cfg := jsoniter.Config{
   SortMapKeys: true,
}.Froze()
// Desired --- register an extension that defines a custom map key sorting function
cfg.RegisterExtension(...some extension...)

m := map[string]int{
   "trump": "should be first",
   "beta": 2,
   "alpha": 1,
}
output, _ := cfg.MarshalToString(m)

// DESIRED OUTPUT
==> {"trump":"should be first","alpha":1,"beta":2}

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions