Created
January 28, 2014 14:11
-
-
Save AutoSponge/8668368 to your computer and use it in GitHub Desktop.
Traverse JSON Schema: node script to transform a json schema into a tree for use with d3.js
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 fs = require( "fs" ); | |
var traverse = require( "traverse" ); | |
var schemaName = process.argv[2]; | |
var schemaPath = "./" + schemaName; | |
if ( !schemaName ) { | |
throw new ReferenceError( "unable to find schema file at '" + schemaPath + "'." ); | |
} | |
var schema = require( schemaPath ); | |
var obj = {}, | |
cache = {}, | |
shadow = {}, | |
title = schema.title || "schema", | |
filename = title + "-map.json"; | |
shadow[title] = {}; | |
traverse( schema ).paths().map(function ( path ) { | |
var prev; | |
return path.reduce( function ( acc, key ) { | |
if ( prev && prev === "properties" ) { | |
acc.push( key ); | |
} | |
prev = key; | |
return acc; | |
}, [] ); | |
} ).filter(function ( path ) { | |
var unique = path.join( "." ); | |
if ( !cache[unique] && path.length ) { | |
cache[unique] = path; | |
return true; | |
} | |
return false; | |
} ).forEach( function ( path ) { | |
traverse( shadow[title] ).set( path, {} ); | |
} ); | |
traverse( shadow ).forEach( function () { | |
var path = this.path.slice( 0 ), | |
child = path.pop(), | |
deep = obj, | |
node, parent; | |
while ( path.length ) { | |
node = path.shift(); | |
parent = deep.children | |
.filter( function ( e ) { | |
return e.name === node; | |
} )[0]; | |
if ( !parent ) { | |
parent = {name: node, children: []}; | |
deep.children.push( parent ); | |
} | |
deep = parent; | |
} | |
if ( child ) { | |
if ( !deep.children ) { | |
deep.children = []; | |
} | |
deep.children.push( {name: child} ); | |
} | |
} ); | |
fs.writeFile( filename, JSON.stringify( obj.children[0], null, " " ), function ( err ) { | |
if ( err ) { | |
throw err; | |
} | |
console.log( "saved " + filename ); | |
} ); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment