Jsonata Wrapper

Class Library
C#
GitHUb Gist

What It Is

A class to allow the easy extraction of data from JSON using JSONata

Status

Last Reviewed:

I use it on this site. However, it’s relatively new, so I don’t know how many edge cases it’s been exposed to

Details

A handy class for query a string of JSON using Jsonata. This wraps Jsonata.Net.Native and combines it with a JSON deserializer to make it easy to get strongly-typed values out of JSON.

The Jsondata.Net.Native library only transforms JSON-to-JSON. So you get a string back – even double-quoted, because remember it’s JSON. This library will deserialize the value for you, into a number of different formats.

And that’s the thing: this library really just a combination of two other libraries. It combines Jsonana.Net.Native and System.Text.Json in a really helpful way. That’s all it does.

Consider the following JSON:

{
  "name": {
    "first": "Deane",
    "last": "Barker"
  },
  "age": 53,
  "dob": "1971-09-03T00:00:00",
  "children": [
    "Alec",
    "Gabrielle",
    "Isabella"
  ],
  "pets": [
    {
      "name": "Lavalette",
      "type": "dog"
    },
    {
      "name": "Turks",
      "type": "cat"
    },
    {
      "name": "Caicos",
      "type": "cat"
    }
  ]
}

It’s very simple to get basic information as strongly-typed values:

var firstName = doc.GetString("$.name.first");  //string
var age = doc.GetNumber("$.age"); // Int32
var dob = doc.GetDate("$.dob"); // DateTime? (null if it doesn't parse)

Since you’re passing full JSONata queries, you can manipulate the return values as desired:

var fullName = doc.GetString("$.name.first & ' ' & $.name.last");

You can get arrays as generic lists:

var kids = doc.GetList<string>("$.children");

And there’s some support for simple object dictionaries (key is property name, value is property value):

var pets = doc.GetDictionaries($".pets"); // List<Dictionary<string,string>>

You can even combine it with the standard System.Text.Json stuff.

public class Pet
{
	public string Name { get; set; }
	public string Type { get; set; }
}

var firstPet = doc.GetObject<Pet>("$.pets[0]";
var allPets = doc.GetList<Pet>("$.pets");

If you want to change the deserialization options (for example, to add custom converters), they’re exposed in a property called DeserializerOptions (which is – perhaps stupidly – actually an instance of JsonSerializerOptions).

Finally, this may sound silly, but since this library just combines two others, ask yourself this – would what I want work if I did it manually using those two libraries? If you think it would, then it will probably work in one step with this library.