Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to sort a Newtonsoft JArray?

Tags:

c#

json.net

Would it be possible to sort the JArray below by col2 for example?

[
    {
        "col1": "thiscol",
        "col2": "thisval"
    },
    {
        "col1": "thiscol2",
        "col2": "thisval2"
    },
    {
        "col1": "thiscol3",
        "col2": "thisval3"
    }
]

If converting this to an Array is the only solution then how could I do this?

like image 907
sparkey Avatar asked Mar 10 '14 16:03

sparkey


1 Answers

I don't think you can sort a JArray in place, but you can sort the contents and load the result into another JArray. Would this work for you?

string json = @"
[
    {
        ""col1"": ""foo"",
        ""col2"": ""bar""
    },
    {
        ""col1"": ""baz"",
        ""col2"": ""quux""
    },
    {
        ""col1"": ""fizz"",
        ""col2"": ""bang""
    }
]";

JArray array = JArray.Parse(json);

JArray sorted = new JArray(array.OrderBy(obj => (string)obj["col2"]));

Console.WriteLine(sorted.ToString(Formatting.Indented));

Output:

[
  {
    "col1": "fizz",
    "col2": "bang"
  },
  {
    "col1": "foo",
    "col2": "bar"
  },
  {
    "col1": "baz",
    "col2": "quux"
  }
]

Fiddle: https://dotnetfiddle.net/2lTZP7

like image 144
Brian Rogers Avatar answered Oct 21 '22 19:10

Brian Rogers