No you cannot use wildcards in a field lookup like you're asking for. Field names should be constant so I'd argue this JSON is poorly implemented (if it were syntactically correct). No JSON generator I'm aware of could convert this JSON to an equivalent language-supported type and that is just bad design.
However you can still use good old fashion looping to do what you want. JObject
implements IEnumerable<string, JToken>
so you can enumerate the fields of the object. You can do your wildcard matching there using LINQ. Unfortunately you'd have to do this at each level where the field name contains data.
//Get all root level fields that start with `Data:`
var dataItems = jsonData.Where(x => x.Key.StartsWith("Data:")).Select(x => x.Value);
foreach (var dataItem in dataItems) {
//Get all customers for the data item
var customers = dataItem["customers"]?.Where(x => x.Key.StartsWith("customer:")).Select(x => x.Value) ?? Enumerable.Empty<JToken>();
};
Of course you can combine these 2 sets of statements into a single statement if you want but I would probably lean toward wrapping all this in an extension method instead. Irrelevant this approach does throw away the field name on Data
and customer
. If you need that information then you'll have to either create a simple wrapper object or use the KeyValuePair<string, JToken>
that the JSON type is returning. To do that remove the Select
calls to filter down to just the value.