jsonjson.netdotliquid

Dotliquid JSON Transformation using JSON.net


Im interested in performing JSON transformations and looked into using dotliquid.

In order to avoid having a POCO for the input JSON just to be able to send it as a variable, I would like to send the deserialised JSON. From my understanding, we can't send dynamic to render method, and JObject or JArray does not work as expected. I Tried deserialising to Dictionary< string, object>, but that could not handle nested JSON structures.

liquid

[
{%- for p in data.names -%}
{
"name" : {{ p.name }}
} {%- unless forloop.Last == true -%},{% endunless %}         
{%- endfor -%}
]

C# code

Template template = Template.Parse(File.ReadAllText("Maps/account.liquid"));             
var json = JsonConvert.DeserializeObject<Dictionary<string, object>>(
    @"{ ""names"":[{""name"": ""John""},{""name"":""Doe""}]  }");              

var jsonHash = Hash.FromAnonymousObject(new { Data = json});

Output

[
  {
    "name" : 
  },         
  {
    "name" :  
  }         
]

I know that Microsoft Logic Apps has implemented a similar feature using dotliquid. https://learn.microsoft.com/en-us/azure/logic-apps/logic-apps-enterprise-integration-liquid-transform

What different ways are there? Do I need to parse the JObject/JArray to a nested Dictionary, or what alternatives are there?


Solution

  • You can get it to work using the DictionaryConverter from Deserialize JSON recursively to IDictionary<string,object> and Hash.FromDictionary

    var json = JsonConvert.DeserializeObject<IDictionary<string, object>>(@"{ ""names"":[{""name"": ""John""},{""name"":""Doe""}]  }", new DictionaryConverter());
    var jsonHash = Hash.FromDictionary(json);
    var templatetest = "<h1>{{device}}</h1><h2>{{speed}}</h2>{% for client in names %}<h4>{{client.name}}</h4>{% endfor %}";
    
    var template = Template.Parse(templatetest);
    var render = template.Render(jsonHash);