Haskell - generating JSON with aeson gives incorrect order of fields Haskell - generating JSON with aeson gives incorrect order of fields json json

Haskell - generating JSON with aeson gives incorrect order of fields


You can use toEncoding method which is available since aeson-0.10 (use aeson-0.11 though, if only possible). In that case you have more control over the generated structure:

instance ToJSON Trend where  toJSON Trend{..} =     object [ "Period"    .= period           , "Africa"    .= africa           , "Americas"  .= americas           , "Asia"      .= asia           ]  toEncoding Trend {..} =    pairs $ "Period"   .= period         <> "Africa"   .= africa         <> "Americas" .= americas         <> "Asia"     .= asia 

Or in case as simple is this, is worth using Generic derivation

instance ToJSON Trend where    toJSON = genericToJSON defaultOptions { fieldLabelModifier = capitaliseFirst }      where        capitaliseFirst (x:xs) = toUpper x : xs        capitaliseFirst []     = []


The reason it is happening is because an Aeson Object is just a HashMap, and when aeson converts the HashMap to text it just serializes the key-value pairs in the order that the HashMap returns them - which probably has no relationship to the order in which the keys were inserted.