Yass
Yass

Reputation: 602

JObject JSON Inner Property sort

I have 3 levels of JSON object and trying to sort based on one of the inner-element.

Here is the sample JSON.

public class Program
{
    public static void Main()
    {
        string myJSON = @"
            {
              ""items"": ""2"",
              ""documents"": [
                {
                  ""document"": {
                    ""libraryId"": ""LIB0001"",
                    ""id"": ""100"",
                    ""elements"": {
                      ""heading"": {
                        ""elementType"": ""text"",
                        ""value"": ""My Heading 1""
                      },     
                      ""date"": {
                        ""elementType"": ""datetime"",
                        ""value"": ""2020-07-03T20:30:00-04:00""
                      }
                    },
                    ""name"": ""My Name 1 "",
                    ""typeId"": ""10ed9f3f-ab41-45a9-ba24-d988974affa7""
                  }
                },
                {
                  ""document"": {
                    ""libraryId"": ""LIB0001"",
                    ""id"": ""101"",
                    ""elements"": {
                      ""heading"": {
                        ""elementType"": ""text"",
                        ""value"": ""My Heading 2""
                      },       
                      ""date"": {
                        ""elementType"": ""datetime"",
                        ""value"": ""2020-07-03T20:30:00-04:00""
                      }         
                    },
                    ""name"": ""My Name 2"",
                    ""typeId"": ""10ed9f3f-ab41-45a9-ba24-d988974affa7""
                  }
                }
              ]
            }";
        
        JObject resultObject = JObject.Parse(myJSON);
        
    
        var sortedObj = new JObject(
            resultObject.Properties().OrderByDescending(p => p.Value)
        );

        string output = sortedObj.ToString();
        Console.WriteLine(output);
        
    
    }
}

I would like to sort based the "date" field. Appreciate any help.

Upvotes: 0

Views: 94

Answers (1)

Guru Stron
Guru Stron

Reputation: 142288

You can replace documents json array with sorted one using json path to sort it:

resultObject["documents"] = new JArray(resultObject["documents"]
        .Children()
        .OrderBy(p => p.SelectToken("$.document.elements.date.value").Value<DateTime>()));
Console.WriteLine(resultObject.ToString());

Or using indexer access:

resultObject["documents"] = new JArray( resultObject["documents"]
        .Children()
        .OrderBy(p => p["document"]["elements"]["date"]["value"].Value<DateTime>()));

Upvotes: 1

Related Questions