TheGamingMaik
TheGamingMaik

Reputation: 83

How to sort a JObject by value

I have some JSON:

{
    "AI": "1",
    "AJ": "0",
    "AM": "0",
    "AN": "0",
    "BK": "5",
    "BL": "8",
    "BM": "0",
    "BN": "0",
    "BO": "4",
    "CJ": "0",
    "CK": "2"
}

I'd like to sort it by number, highest to lowest, and get the property with the highest number by just writing the first index of the JSON. Can you help me?

This is what I have so far:

string voteJson = File.ReadAllText("vote.json");
Object voteObj = JObject.Parse(voteJson);

//How to sort the object here?

//Saving it 
string output = Newtonsoft.Json.JsonConvert.SerializeObject(voteObj, 
    Newtonsoft.Json.Formatting.Indented);
File.WriteAllText("vote-sorted.json", output);

Upvotes: 7

Views: 9841

Answers (1)

Brian Rogers
Brian Rogers

Reputation: 129717

Although the JSON spec defines a JSON object as an unordered set of properties, Json.Net's JObject class does appear to maintain the order of properties within it. You can sort the properties by value like this:

JObject voteObj = JObject.Parse(voteJson);

var sortedObj = new JObject(
    voteObj.Properties().OrderByDescending(p => (int)p.Value)
);

string output = sortedObj.ToString();

You can then get the property with the highest value like this:

JProperty firstProp = sortedObj.Properties().First();
Console.WriteLine("Winner: " + firstProp.Name + " (" + firstProp.Value + " votes)");

Working demo: https://dotnetfiddle.net/dptrZQ

Upvotes: 12

Related Questions