I just found a html to json parser, himalaya, and i though this needs a json to html parser.
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
var mariana = { | |
parse : function(json){ | |
return mariana.checkFragment(json); | |
}, | |
checkFragment : function(arr){ | |
var out = ''; | |
for(fragment of arr){ | |
switch(fragment.kind){ | |
case "element": out += mariana.element(fragment); break; | |
case "text": out += fragment.content; break; | |
case "comment": out += '<!--'+fragment.content+'-->'; break; | |
} | |
} | |
return out; | |
}, | |
element : function(obj){ | |
var out = '<'+obj.tagName+mariana.attributes(obj)+'>'; | |
var voidTags = [ | |
"!doctype", "area", "base", "br", "col", "command", | |
"embed", "hr", "img", "input", "keygen", "link", | |
"meta", "param", "source", "track", "wbr"]; | |
if(voidTags.indexOf(obj.tagName) === -1){ | |
if(typeof obj.children !== 'undefined'){ | |
out += mariana.checkFragment(obj.children); | |
} | |
out += '</'+obj.tagName+'>'; | |
} | |
return out; | |
}, | |
attributes : function(obj){ | |
var out = []; | |
if(typeof obj.id !== 'undefined'){ | |
out[out.length] = 'id="'+obj.id+'"'; | |
} | |
if(typeof obj.className !== 'undefined'){ | |
out[out.length] = 'class="'+obj.className.join(' ')+'"'; | |
} | |
if(typeof obj.dataset !== 'undefined'){ | |
for(key in obj.dataset){ | |
out[out.length] = 'data-'+key+'="'+obj.dataset[key]+'"'; | |
} | |
} | |
var excluded = ['id', 'tagName', 'className', 'dataset', 'children', 'kind']; | |
for(key in obj){ | |
if(excluded.indexOf(key) == -1){ | |
out[out.length] = key+'="'+obj[key]+'"'; | |
} | |
} | |
return out.length !== 0 ? ' '+out.join(' ') : ''; | |
} | |
}; |
It isn't fancy, but it gets the work done and it's readable.
No comments:
Post a Comment