I have a Json “database” of sorts, and am trying to extract contents from it using Newtonsoft Json.Net LINQ.
The goal is to extract a property from the items in a child array contained within an item in a parent array. The item in the parent array will be selected by a key property. The “outer” element is an array with one entry, the “inner” element is an array of two parent entries, each of which has a “key” and an array of child “items.” Looking to match the inner parent item by its key, and then extract the child “itemid” properties of all items in the child array into an IList.
file at filePath contains:
{
"outer":
[
{
"inner":
[
{
"key": "AAA",
"items":
[
{ "itemid": "a1" }
]
},
{
"key": "BBB",
"items":
[
{ "itemid": "b1" },
{ "itemid": "b2" }
]
}
]
}
]
}
I’m thinking the extraction query would look something like what is shown below, but neither this nor any of the dozens of variations of this I’ve tried have been successful. In some variations it seems to work all the way up to the final selection of the correct inner “items” but then falls apart on me when trying to dig out the array of “itemid.” Any clues what is wrong here? I’m willing to split this up into two separate queries if need be.
public IList<string> FindMatchingItems(string filePath, string id)
{
JObject JsonLinq = JObject.Parse(File.ReadAllText(filePath));
return JsonLinq["outer"].First()["inner"].Children()
.First(inner => inner["key"].ToString() == id)
.Select(selected => selected["items"].Children()["itemid"].ToString())
.ToList();
}
void Query(string filePath)
{
var ayes = FindMatchingItems(filePath, "AAA");
// ayes contains [] { "a1" }
var bees = FindMatchingItems(filePath, "BBB");
// bees contains [] { "b1", "b2" }
}