Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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);
like image 211
TheGamingMaik Avatar asked Jan 09 '18 20:01

TheGamingMaik


1 Answers

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

like image 85
Brian Rogers Avatar answered Oct 16 '22 16:10

Brian Rogers