2

Straight and simple, following is a sample Json:

{
    "2014-05-27": 292,
    "2014-05-06": 323,
    "2014-05-21": 212,
    "2014-05-22": 238,
    "2014-05-23": 219
}

As clearly visible the keys are the dates and values are some counter. I need to sort this JSON on basis of dates. I am programming in java and using Jackson library if that helps.

3
  • What do you mean ? You want to have a JSON string with the lines written in the alpha order of the keys ? Commented Jun 5, 2014 at 15:31
  • 3
    Json doesn't have an order. Parse the JSON, generate your application model objects, and sort those. Also, that is a JSON object, not an array. Commented Jun 5, 2014 at 15:31
  • Yeah so I can convert it to a Map and then sort the Map? Is that what you're suggesting? Commented Jun 5, 2014 at 15:33

2 Answers 2

3

You could convert that JSON to a Map, then sort that Map, and then convert it back to JSON.

Sign up to request clarification or add additional context in comments.

Comments

2

According to the JSON spec:

An object is an unordered set of name/value pairs.

and

An array is an ordered collection of values.

If you wanted to do the sorting in your Java code, you could sort them by date into a list and pass the list back in your response. Jackson will do the work of converting the list into an array and preserving the order. This approach would require you to convert your key:values to objects. The objects that populate your array would look similar to this:

{
    "date": "2014-05-27",
    "value": 292
}

You will retain ordering guarantees by using an array. Using an object you have no guarantees.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.