Search code examples
jsonjson2html

How to define recursive transforms for J2H?


I'm evaluating to use J2H (http://json2html.com/examples/) to render JSON structures.

My JSON are complex trees, with many repeated (recursive) structures.

My question is about how to define a transform that can be applied at many levels of the JSON tree when it finds nodes of the same type/structure (I can add type or class attributes to know which nodes are of the same type).

Example:

+ root type=node
  + child type=attribute
    + child type=node
      + child type=attribute
  + child type=attribute
    + child type=node_primitive
      + child type=primitive
  + child type=attribute
    + child type=node

On that tree we have types: node, attribute, node_primitive and primitive that can be on different levels of the tree. And nodes of the same type will have the same structure.


Solution

  • You should be able to do something like this using inline functions and nested transforms (http://json2html.com/examples/#example-basic-nested)

    For example if you want to have a specific child based on a type json field you can do something like this

    var transforms = {
        'attribute':{'<>':'div','text':'Attribute'},
        'node':{'<>':'div','text':'Node'},
        'list':{'<>':'li','html':function(){
            return( json2html.transform(this,transforms[this.type]) );    
        }},
    
    var data = [
        {'type':'node'},
        {'type':'attribute'}
    ];
    
    document.write( json2html.transform(data,transforms.list) );
    

    If your JSON structure has more than one level of depth you could recursively call the following within the inline function of the root node.

    json2html.transform(this.child,transforms.list)