Created
January 14, 2019 12:19
-
-
Save akx/9affd537beb5c67c27f589be24f592ae to your computer and use it in GitHub Desktop.
c2j -- dsl for generating json
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
#!/usr/bin/env python3 | |
import json | |
import sys | |
class c2j: | |
def __init__(self): | |
self.stack = [] | |
self.root = None | |
self.current_key = None | |
@property | |
def top(self): | |
return self.stack[-1] | |
def contain(self, obj): | |
if not self.stack: | |
return | |
if isinstance(self.top, dict): | |
if not self.current_key: | |
raise ValueError("no current key") | |
self.top[self.current_key] = obj | |
self.current_key = None | |
elif isinstance(self.top, list): | |
self.top.append(obj) | |
else: | |
raise TypeError("invalid value on stack") | |
def append(self, obj): | |
if not self.stack: | |
self.root = obj | |
self.stack.append(obj) | |
def process_line(self, line): | |
line = line.rstrip("\r\n").split(None, 1) | |
verb = line.pop(0).lower() | |
if verb == "obj": | |
obj = {} | |
self.contain(obj) | |
self.append(obj) | |
elif verb == "array": | |
obj = [] | |
self.contain(obj) | |
self.append(obj) | |
elif verb == "key": | |
if not isinstance(self.top, dict): | |
raise ValueError("can not use key when no obj on top of stack") | |
self.current_key = line[0] | |
elif verb == "string": | |
self.contain(line[0]) | |
elif verb == "number": | |
self.contain(float(line[0]) if "." in line[0] else int(line[0])) | |
elif verb == "true": | |
self.contain(True) | |
elif verb == "false": | |
self.contain(False) | |
elif verb == "null": | |
self.contain(None) | |
elif verb == "end": | |
self.stack.pop(-1) | |
else: | |
raise ValueError("unknown verb " + verb) | |
if __name__ == "__main__": | |
c = c2j() | |
for line in sys.stdin: | |
c.process_line(line) | |
print(json.dumps(c.root, indent=2, sort_keys=True)) |
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
#!/bin/bash | |
( | |
echo obj | |
for x in a b c d; do | |
echo key $x | |
echo array | |
echo number $RANDOM | |
echo number $RANDOM | |
echo number $RANDOM | |
echo end | |
done | |
) | python3 c2j.py |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment