Get all keys of a JObject that meet a certain criteria

I have a json file that I deserialize into a jObject. I need to find all fields that start with “DB”, so that I can adjust these fields according to their respective names and write it into a new json file. The JObject looks like this:

 {
    "page": 1,
        "data": [
            {
                "db001": "text",
                "db002": "text",
                "db003": {
                    "item_1": "xxx",
                    "item_2": "xxx",
                    "item_3": "xxx"
                },
                "db004": "text",
                "db005": "text",
                "db006": "text",
            }
     ]
}

An example code which I was thinking was something along the lines of…

for each field in jObject.Where(function (f) f.StartsWith("DB"))

However, argument type JObject throws an error saying “.Where is not a member of newtonsoft.json.linq.jobject”

I thought I could use a LINQ query to get all instances of these keys starting with “DB” or containing this syntax, but I’m struggling to find the right query. Every other type of syntax and query results in either nothing or “Object reference not set to an instance of an object.”

Can someone point me the right way? I’m out of Google searches at this point…

Hi,

I think something like this should help in your situation:

dictStartsDb = json.Properties.Where(Function(z) z.Name.StartsWith(“db”)).ToDictionary(Function(x) x.Name, Function(x) x.Value)

It returns a dictionary, where keys are the JSON keys and the values the Jtokens. Or you could change the return type.

Gio

@COS
we do have following:

grafik

  • a JArray - red line
  • a JObject - yellow mark

as we could also expect that multiple JObjects can technically occurs within the array we have handle this in LINQ as well

Variables:
grafik

Flow:
grafik

LINQ:
(From o In myJObject(“data”).Cast(Of JObject)
Let arrProps = o.Properties.Where(Function (x) x.Name.toUpper.StartsWith(“DB”)).ToArray
Select arrProps).toList

line1 - iterate over the array items and cast it to JObject
line2 - filter the current looped JObject ’ properties on the name (starts with DB) and return result as array
line3 - return the filtered properties array and compile it to a list

Result:
grafik

So for first JObject of JArray we can access the properties by:
grafik

accessing the names:
grafik

Find starter help here:
FilterArray_JObjectPropName.xaml (5.2 KB)

json:
data.json (408 Bytes)