INI to JSON Converter in Python
A Python script that reads an INI configuration file with configparser and prints it as nested JSON, converting numeric and boolean values.
Project
python-ini-to-json
Entry point: ini_to_json.py
Install
python --versionRun
python ini_to_json.py config.iniTest
python ini_to_json.py config.iniExpected output
Prints the INI file as nested JSON with sections as objects and typed scalar values.Dependencies
- python >=3.10
What it does
Converts an INI file into JSON using configparser, which is the quick way to move a legacy config into a modern toolchain.
import configparser
import json
import sys
def coerce(value):
lowered = value.strip().lower()
if lowered in {"true", "yes", "on"}:
return True
if lowered in {"false", "no", "off"}:
return False
try:
return int(value)
except ValueError:
pass
try:
return float(value)
except ValueError:
return value
def convert(path):
parser = configparser.ConfigParser()
parser.read(path)
return {section: {key: coerce(value) for key, value in parser.items(section)} for section in parser.sections()}
def main():
print(json.dumps(convert(sys.argv[1]), indent=2))
if __name__ == "__main__":
main()
Scalar values are coerced to integers, floats, or booleans so downstream JSON consumers get real types rather than strings.
Run and verify
printf '[server]\nport = 8080\ndebug = true\nname = demo\n' > config.ini
python ini_to_json.py config.ini
Create a small INI file with a number and a boolean, then convert; section names become top-level keys.
Expected Output
For the sample section the script should print numbers and booleans as real JSON types. The output is:
{
"server": {
"port": 8080,
"debug": true,
"name": "demo"
}
}
Section names become object keys, numeric strings become numbers, and true-like values become the JSON boolean true.
Limitations
Type coercion is heuristic and can convert a numeric-looking string that should stay text; for strict typing, keep values as strings and coerce at the consumer.