0

I'm looking for a way to pass a single string selector to get a value from hierarchical JSON. This selector could be id, location.name, or even deeper, it has to be dynamic.

I have this JSON:

{
"generatedAt": "2022-01-01 02:03:25",
"myitems": [
{
    "id": "1795089",
    "location": {
        "name": "Myplace",
        "countryCode": "DE"\
    },
}
,
{
    "id": "1795070",
    "location": {
        "name": "Roseplace",
        "countryCode": "US"
    },
}

],
"count": 2
}

I want to select nested values by a SINGLE selector. E.g. location.name. I want this because I want to store the selector in a single field in my database. I have tried this:

Dim obj As JObject = JObject.Parse(json)
Dim jsonArray As JArray = DirectCast(obj("myitems"), JArray)
    
For Each item In jsonArray
    item("id").Value(Of String) 'works
    item("location")("name").Value(Of String) 'works    
    item("location.name").Value(Of String) 'does NOT work
Next

I considered storing the selector in my database like location.name and then when executing the selector in my code, first splitting that selector by ., and then build it like item(selectorpart(0))(selectorpart(1)).Value(Of String) However, I have a lot of fields that I need to select and it would be a lot of extra code if I need to split each selector first. Also because many times my JSON is not as nested as above and I wouldn't need to split the selector at all.

How could I do this?

I checked here, but the described requirement seems different than mine. I checked here but it doesn't apply to nested structures. Also, I'm reading JSON feeds from different providers so I can't simply create a single class as was suggested in some other threads, and I don't want to have to map each feed structure to a class.

4
  • If item("location")("name").Value(Of String) works, then what is your problem? What do you mean by single dynamic selector? Do you mean a JSONPath query string? Commented May 5, 2022 at 12:37
  • 1
    If a JSONPath query is what you want, this looks to be a duplicate of Searching for a specific JToken by name in a JObject hierarchy and/or What is the JSON.NET equivalent of XML's XPath, SelectNodes, SelectSingleNode?. Your query would be obj.SelectTokens("myitems[*].location.name") from the root, or item.SelectToken("location.name") while looping through the array. Commented May 5, 2022 at 12:45
  • Does that answer your question? Commented May 5, 2022 at 12:54
  • 1
    I was looking for the right terminology indeed. But thanks, item.SelectToken("location.name") is exactly what I was looking for! Commented May 5, 2022 at 14:15

0

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.