Created
September 28, 2017 14:17
-
-
Save jradmacher/85dca1b09b784e092ae0c2016843ed2b to your computer and use it in GitHub Desktop.
convert INI file to json, skipping all garbage data
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
# -*- 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