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);
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With