Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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://docs.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?

like image 548
Fredrik Jacobson Avatar asked May 10 '18 20:05

Fredrik Jacobson


People also ask

How do you call JSON data in Python?

Instead of the JSON loads method, which reads JSON strings, the method used to read JSON data in files is load(). The load() method takes up a file object and returns the JSON data parsed into a Python object. To get the file object from a file path, Python's open() function can be used.

What is B in JSON?

JSON-B is a standard binding layer for converting Java objects to/from JSON messages. It defines a default mapping algorithm for converting existing Java classes to JSON, while enabling developers to customize the mapping process through the use of Java annotations.


1 Answers

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);
like image 124
Sixx Avatar answered Sep 27 '22 23:09

Sixx