Skip to content

Instantly share code, notes, and snippets.

@jradmacher
Created September 28, 2017 14:17
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 jradmacher/85dca1b09b784e092ae0c2016843ed2b to your computer and use it in GitHub Desktop.
Save jradmacher/85dca1b09b784e092ae0c2016843ed2b to your computer and use it in GitHub Desktop.
convert INI file to json, skipping all garbage data
# -*- coding: utf-8 -*-
import json
import sys
import re
from configparser import (ConfigParser, MissingSectionHeaderError,
ParsingError, DEFAULTSECT)
def isIniLine(line):
#filter for lines with
# [section]
# name = value and more blah
#
# multiline/line continuation is not supported
header = re.compile("\[.+\]")
value = re.compile("[a-zA-Z0-9_]+\s*=\s*\S+")
return header.match(line) or value.match(line)
if __name__ == "__main__":
if len(sys.argv) > 1:
f = open(sys.argv[1])
else:
f = sys.stdin
lines = f.readlines()
f.close()
filtered=filter(isIniLine,lines)
cfg = ConfigParser()
cfg.readfp(filtered)
config = {}
for section in cfg.sections():
config[section] = {}
for name, value in cfg.items(section):
config[section][name] = [x.strip() for x in value.split() if x]
if len(config[section][name]) == 1:
config[section][name] = config[section][name][0]
elif len(config[section][name]) == 0:
config[section][name] = ''
print (json.dumps(config))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment