Search code examples
c#arraysjsonjson.netjsonpath

How to use JSONPath (or any other option) to query an unnamed JSON array?


A REST API service provides the following JSON to my C# code:

[
  {
    "contentUri": "https://somewhere.com/aGuid1",
    "contentId": "2"
  },
  {
    "contentUri": "https://somewhere.com/aGuid2",
    "contentId": "3"
  },
  {
    "contentUri": "https://somewhere.com/aGuid3",
    "contentId": "4"
  }
]

Above JSON is simplified and the actual response is a VERY large string ,so is string manipulations will be costly and memory intensive.

The problem is that the above JSON Array does not have a name. so I am not able to parse it into an JArray unless I manipulate the JSON string and add a name to it. I like to avoid that.

I can perfectly parse above JSON into a JToken. Now I like to query within the JToken by using JToken.SelectToken and JSONPath

  • What JSONPath returns all of the elements in above JSON array?

  • What JSONPath returns all of the contentUri values in above JSON array?

I've tried many JSONPath queries, but no lock since the array does not have a name.


Solution

  • You can very easily parse the above json into a JArray:

    JArray array = JArray.Parse(jsonString);
    

    To get all objects in the array, you don't need a JSONPath expression, just loop over the array:

    foreach (JObject child in array)
    {
        Console.WriteLine("contentUri: " + (string)child["contentUri"]);
        Console.WriteLine("contentId: " + (string)child["contentId"]);
    }
    

    For completeness, the equivalent JSONPath expression to get all the array values is [*]. But it doesn't really buy you anything here.

    To get all the contentUri values only, you can use SelectTokens with the JSONPath [*].contentUri:

    foreach (JToken uri in array.SelectTokens("[*].contentUri"))
    {
        Console.WriteLine(uri);
    }
    

    Alternatively, you could just Select them like this:

    foreach (string uri in array.Select(t => (string)t["contentUri"]))
    {
        Console.WriteLine(uri);
    }
    

    Fiddle: https://dotnetfiddle.net/C2gIWX