Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Optionally sort Aeson Values in Arrays #21

Open
wants to merge 3 commits into
base: master
Choose a base branch
from

Conversation

tdox
Copy link

@tdox tdox commented Jan 4, 2017

Motivation: For an array that contains objects, whose keys are identical but whose values are different, I need a way to consistently encodePretty so that the objects are always encoded in the same order.

This change adds support for sorting an array of Values. Library users can specify their own comparison function (Value -> Value -> Ordering) or use a helper function (mkBasicValueCompare) to make a comparison function that orders the values in a reasonable way.

@informatikr
Copy link
Owner

First of all: thanks for the PR.

I understand the requirement for a way to sort arrays, but I am wondering if this is the right place. JSON arrays are already ordered, so what you are doing is technically not pretty-printing but modifying the data. Have you thought about alternatives, such as

  1. sorting the arrays in the ToJSON instance where they are created, or
  2. writing a function sortArray :: (Value -> Value -> Ordering) -> Value -> Value and apply it before pretty-printing?

I am not necessarily opposed to merging, if you think this is the best place. But I would like to hear some argument for it.

@tdox
Copy link
Author

tdox commented Jan 6, 2017

Thanks for your library!

My use case is that I'm using wreq with aeson (and now aeson-pretty) to run what are sometimes called "golden" regression tests of a REST api. During each test, I'm calling the api, getting back some json, and comparing that with previously saved json, which represents the standard or "golden" result. So it's the REST api that is generating the json, not my code. My tests were failing because the json arrays of json values were being returned in a different order, even thought the api was being called the same each time. The only difference was that the order in the arrays were different, the data was identical. Now with my patch to aeson-pretty, I can be sure that data in the arrays are sorted and printed the same way each time I print the api's output json.

I may be able to use your sortArray suggestion somewhere in my code. I'll investigate that possibility and reply later.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

Successfully merging this pull request may close these issues.

2 participants