Last active
August 26, 2024 11:21
-
-
Save deanebarker/f2d91eae14ab1055c767195764ec33a1 to your computer and use it in GitHub Desktop.
A Fluid value that allows extraction of data from JSON using JSONata.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// Information on JSONdata: https://jsonata.org/ | |
// Requires this class also: https://gist.github.com/deanebarker/d9983155603d1adf26197787a9c74ae4 | |
// in C# | |
var json = GetABunchOfJson(); | |
var context = new TemplateContext(); | |
context.SetValue("json", new JsonataValue(json)); | |
/* In Liquid... | |
<ul> | |
{% for item in json.query("$.entries") %} | |
<li>{{ item.value("$.name.last") }}, {{ item.value("$.name.first") }}</li> | |
{% endfor %} | |
</ul> | |
*/ | |
public class JsonataValue : ObjectValueBase | |
{ | |
private JsonataDoc doc; | |
private string json; | |
public JsonataValue(string json) : base(json) | |
{ | |
doc = new JsonataDoc(json); | |
this.json = json; | |
} | |
public override ValueTask<FluidValue> GetValueAsync(string name, TemplateContext context) | |
{ | |
if (name.ToLower() == "value") | |
{ | |
return new FunctionValue((a, c) => | |
{ | |
var queryText = a.At(0).ToStringValue(); | |
return new StringValue(doc.GetString(queryText)); | |
}); | |
} | |
if (name.ToLower() == "query") | |
{ | |
return new FunctionValue((a, c) => | |
{ | |
var queryText = a.At(0).ToStringValue(); | |
var queryResult = new JsonataQuery(queryText).Eval(json); | |
var jsonDoc = JsonDocument.Parse(queryResult); | |
return new ArrayValue(jsonDoc.RootElement.EnumerateArray().Select(s => new JsonataValue(s.ToString()))); | |
}); | |
} | |
return NilValue.Instance; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment