Skip to content

Instantly share code, notes, and snippets.

@facchinm
Last active August 29, 2015 14:21
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save facchinm/aad5ba263158065923d2 to your computer and use it in GitHub Desktop.
Save facchinm/aad5ba263158065923d2 to your computer and use it in GitHub Desktop.
dot notation to json
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