Last active
August 29, 2015 14:21
-
-
Save facchinm/aad5ba263158065923d2 to your computer and use it in GitHub Desktop.
dot notation to 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
import itertools | |
import collections | |
import pprint | |
import json | |
import os | |
import dicttoxml | |
def dot_to_json(a,b): | |
output = {} | |
for index, key in enumerate(a): | |
value = b[index] | |
path = key.split('.') | |
#handle fields with nth explicit nesting | |
try: | |
value = value.strip().replace("\"","") | |
target = reduce(lambda d, k: d.setdefault(k, {}), path[:-1], output) | |
target.update({path[-1] : value}) | |
lastbroken = "" | |
except AttributeError: | |
#shame on the creator of the original config file | |
if lastbroken == "": | |
lastbroken = lastpath[-1] | |
path = [w.replace(lastbroken, lastbroken+"_cfg") for w in path] | |
target = reduce(lambda d, k: d.setdefault(k, {}), path[:-1], output) | |
target.update({path[-1] : value}) | |
lastvalue=value | |
lastpath=path | |
return output | |
filenames = [ "hardware/avr/boards.txt", "hardware/avr/platform.txt", "hardware/sam/boards.txt", "hardware/sam/platform.txt" ] | |
s = {} | |
for filename in filenames: | |
s_t = {} | |
with open(filename) as f: | |
content = f.readlines() | |
listKey = [] | |
listValues = [] | |
for element in content: | |
a = element.split("=") | |
b = a[0].split(".") | |
if (len(a) == 2 and element[0]!="#"): | |
listKey.append(a[0]) | |
listValues.append(a[1]) | |
s_t = dot_to_json(listKey, listValues) | |
pp = pprint.PrettyPrinter() | |
#pp.pprint(s) | |
core = "arduino" | |
base = os.path.basename(filename) | |
arch = os.path.dirname(filename).split("/")[-1] | |
module = os.path.splitext(base)[0] | |
baseStr = core+" "+arch+" "+module | |
baseList = baseStr.split(" ") | |
print(baseList) | |
target = reduce(lambda d, k: d.setdefault(k, {}), baseList[:-1], s) | |
target.update({baseList[-1] : s_t}) | |
j = json.dumps(s, ensure_ascii=True) | |
xml = dicttoxml.dicttoxml(s, attr_type=False) | |
pp.pprint(j) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment