Last active
January 29, 2016 18:39
-
-
Save rjpower/51972e587ee6e431580a to your computer and use it in GitHub Desktop.
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
from data import ROOT | |
class SchemaBuilder(object): | |
def __init__(self, prefix=''): | |
self.last_key = '' | |
self.prefix = prefix | |
self.results = {} | |
def parse(self, obj, my_key='Root'): | |
if obj is None: return 'Any' | |
if isinstance(obj, list): | |
if not obj: return 'List[Any]' | |
return 'List[%s]' % self.parse(obj[0], my_key) | |
if isinstance(obj, dict): | |
my_name = self.prefix + my_key[0].upper() + my_key[1:] | |
parts = ['val %s: %s' % (k, self.parse(obj[k], k)) for k in obj] | |
self.results[my_name] = 'case class %s(%s)' % (my_name, ',\n'.join(parts) | |
) | |
return my_name | |
if isinstance(obj, (unicode, str)): return 'String' | |
if isinstance(obj, float): return 'Double' | |
if isinstance(obj, int): return 'Int' | |
return 'N/A' | |
builder = SchemaBuilder('Reddit') | |
builder.parse(ROOT) | |
for v in builder.results.values(): | |
print v, '\n' |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Feeling too lazy to make a schema for your random JSON document? But also too lazy to work with an untyped interface? Then this is for you! It automatically infers a passable set of case classes corresponding to a JSON document!