DavidB
DavidB

Reputation: 2596

Querying JSON with JSON .NET

{
   "kind": "folderTree",
   "data":
   [
       {
           "id": "IEAAALNZI7777777",
           "title": "Root",
           "childIds":
           [
               "IEAAALNZI4ADAKBQ",
               "IEAAALNZI4ADAMBQ",
               "IEAAALNZI4ADAMBR"
           ],
           "scope": "WsRoot"
       },
       {
           "id": "IEAAANE7I7777777",
           "title": "Root",
           "childIds":
           [
               "IEAAANE7I4AC2NTX"
           ],
           "scope": "WsRoot"
       },
       {
           "id": "IEAAALNZI7777776",
           "title": "Recycle Bin",
           "childIds":
           [
               "IEAAALNZI4ADALZ2",
               "IEAAALNZI4ADAL52",
               "IEAAALNZI4ADALR3"
           ],
           "scope": "RbRoot"
       }
   ]
}

Im trying to query the following json structure, searching the child items I want to return the id for a given title.

I am trying something like this:

var folder = json["data"].Children().Where(x => x["Title"] == "Root");

But I'm not sure of the correct syntax

Upvotes: 2

Views: 1918

Answers (1)

dbc
dbc

Reputation: 116731

You can use SelectTokens to query LINQ to JSON objects. It supports JSONPath query syntax including wildcards. You can then further narrow down the search with a Where clause:

var folders = json.SelectTokens("data[*]").Where(t => (string)t["title"] == "Root").ToList();

It also supports filtering of array entries based on property values if you don't want the extra Where clause:

var folders = json.SelectTokens("data[?(@.title == 'Root')]").ToList();

Both of the above do the same thing. Incidentally, you've got two folders whose title is "Root" in your JSON, so your query will return multiple results.

Upvotes: 2

Related Questions