Search code examples
c#jsondynamicexpandoobject

Addressing JSON in C# dynamically


I wish to write some C# which allows the client to provide a JSON string and query string. The query string would then be used to address values in the JSON object.

For example, if I had this JSON:

{
  "head": "big",
  "fingers": [
    "one", "thumb",
    "two", "ring"
  ],
  "arm": {
    "elbow", "locked"
  }
}

And this query string:

"fingers.two"

I would want to return the value "ring".

Is this (or something like it) possible in C#?

I have tried using the ExpandoObject class, but this does not allow dynamic runtime inspection:

var json = JsonConvert.DeserializeObject<ExpandoObject>(jsonStr);

As far as I can tell, the discovery of values on the json variable needs to be done at code time, rather than runtime, which means I cannot dynamically find values being queried for.


Solution

  • JSONPath does this

    Assuming the following JSON (fixed a few syntax errors in the original)

    {
      "head": "big",
      "fingers": {
        "one":"thumb",
        "two":"ring"
      },
      "arm": {
        "elbow": "locked"
      }
    }
    

    And this query

    MyJObjectOrToken.SelectToken("fingers.two")

    You will get the following output:

    [
        "ring"
    ]
    

    It should be trivial then to extract the value as a string using JSON.Net methods and return the result to your user.

    Support for JSONPath is built into JSON.Net

    https://www.newtonsoft.com/json/help/html/SelectToken.htm