Skip to content

Instantly share code, notes, and snippets.

@threepointone
Created January 14, 2015 21:46
Show Gist options
  • Save threepointone/26dffd540c9e438c466f to your computer and use it in GitHub Desktop.
Save threepointone/26dffd540c9e438c466f to your computer and use it in GitHub Desktop.
jade -> json trees
var _ = require('underscore'),
Parser = require('jade/lib/parser');
module.exports = {
toJSON: toJSON,
fromJSON: fromJSON
}
function toJSON(src, options) {
var parser = new Parser(src),
parsed = parser.parse(),
compiled = _.map(parsed.nodes, compile);
return compiled;
}
function fromJSON(o) {
return decompile(o);
}
function compile(node) {
if (node.val) {
return {
type: 'text',
props: {
value: node.val
}
};
}
var o = {
type: node.name,
props: _.reduce(node.attrs, (o, a) => {
o[a.name] = eval('(' + a.val + ')');
return o;
}, {}),
}
if (node.block && node.block.nodes && node.block.nodes.length > 0) {
o.children = _.map(node.block.nodes, compile);
}
return o;
}
function tabs(n) {
return new Array(n + 1).join(' ');
}
function decompile(node, depth) {
depth = depth || 0;
var str = tabs(depth);
if (node.type === 'text') {
str += '| ' + node.props.value
return str;
}
str += node.type + (node.props ? ('(' + _.map(node.props, (v, k) => k + '=' + JSON.stringify(v)).join(' ') + ')') : '') + '\n';
if (node.children) {
str += _.map(node.children, c => decompile(c, depth + 1)).join('')
}
return str;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment