JSON5 vs XML, INI and .env

Four ways to write settings down, and four very different ideas of what a setting is.

JSON5 describes objects, arrays and typed values. XML describes a tree of elements with attributes and text. INI describes sections of key and value strings, and a .env file is a flat list of strings.

Below, one configuration appears in all four, followed by comments, schemas, parsers, XML entity attacks, conversion code that was actually run, and the cases where XML or INI is the better tool. The conversion scripts were run on real parsers, and their output is shown.

One service configuration shown on four screens as JSON5, XML, INI and a .env file

TL;DR: Choose JSON5 for nested, typed settings in code you control. Choose XML for marked-up text, mixed vocabularies, or an ecosystem that already validates with XSD. Choose INI for short, flat files edited by hand. Use .env to set environment variables, not to model structure.

Table icon

At a Glance

PropertyJSON5XML 1.0INI.env
Governing document1.0.0 specificationW3C RecommendationNone shared; each parser sets rulesNone shared; each loader sets rules
StructureObjects and arraysElement treeSections of keysFlat keys
NestingAny depthAny depthConvention onlyConvention only
Value typesString, number, boolean, null, object, arrayText, unless a schema assigns typesStrings; some parsers convertStrings
Comments// and /* */<!-- -->; or #, by parser#
Mixed text and markupNoYesNoNo
Schema languageJSON Schema, on parsed dataDTD, XSD and othersNone standardNone standard

"None shared" is the most consequential cell. XML 1.0 (Fifth Edition, November 26, 2008) and JSON5 1.0.0 (March 2018) each say what a conforming parser must accept. INI and .env are families of dialects, so a file is only defined relative to the program that reads it.

Code file icon

The Same Config in All Four

The settings include the awkward cases on purpose: a number, a boolean, a postal code with a leading zero, an empty value, a list and one level of nesting. These four files are the exact inputs used for the conversion tests further down.

JSON5

// server settings { name: 'orders-api', port: 8080, debug: false, zip: '02134', owner: null, hosts: ['a.example.com', 'b.example.com'], database: { host: 'db.internal', timeout: 2.5, }, }

XML

<?xml version="1.0" encoding="UTF-8"?> <!-- server settings --> <config name="orders-api"> <port>8080</port> <debug>false</debug> <zip>02134</zip> <owner/> <host>a.example.com</host> <host>b.example.com</host> <database host="db.internal" timeout="2.5"/> </config>

INI

; server settings [server] name = orders-api port = 8080 debug = false zip = 02134 owner = hosts = a.example.com, b.example.com [database] host = db.internal timeout = 2.5

.env

# server settings APP_NAME=orders-api PORT=8080 DEBUG=false ZIP=02134 OWNER= HOSTS=a.example.com,b.example.com DATABASE__HOST=db.internal DATABASE__TIMEOUT=2.5 # seconds

Only the first file says on its own that the port is a number, the owner is absent rather than empty, and hosts is a list. In the other three, that knowledge lives in a schema or in the program.

Structure icon

Data Model Differences

JSON5: values with types

A document is one value. Objects map names to values, arrays keep order, and the literal syntax decides the type, so 8080 and '8080' differ. Numbers may be hexadecimal, may start or end with a decimal point, and include Infinity and NaN. Leading zeros are not allowed: writing zip: 02134 fails in the reference JavaScript parser; for the input {zip: 02134} it reports JSON5: invalid character '2' at 1:8, which is why the postal code is quoted. Names should be unique; the specification calls the handling of duplicates unpredictable, and the reference parser keeps the last one. See data types.

XML: elements, attributes and text

XML gives you two places for the same fact. host="db.internal" and <host>db.internal</host> are both reasonable, and they are not interchangeable:

BehaviorAttributeChild element
May repeatNo: a name appears once per tagYes
Order significant to the XML specificationNoPreserved as document structure
Can contain further structureNoYes
Takes the default namespaceNoYes

There is also no array syntax. A list is repeated elements, so a reader cannot tell from one <host> whether it is a single value or a list of length one. There is no null either: <owner/> is an element with no content, and meaning "unknown" is a convention or a schema feature.

Namespaces

Namespaces in XML 1.0 (Third Edition, December 8, 2009) ties element and attribute names to URI references so vocabularies from different authors can share a document without clashing. One detail surprises people: a default namespace declaration does not apply to unprefixed attributes.

<config xmlns="https://example.com/ns/app" xmlns:log="https://example.com/ns/logging"> <level>3</level> <log:level>warn</log:level> </config>

JSON5 has nothing like this. You nest each tool's settings under its own key, or you adopt a prefix convention that no parser enforces.

Mixed content

An XML element may interleave character data and child elements: <p>Press <b>Save</b> to continue.</p>. This is what XML is unusually good at. In JSON5 you would have to invent an array of fragments, such as ['Press ', {b: 'Save'}, ' to continue.'], and every consumer must learn your invention. Libraries need care too: in Python's ElementTree the paragraph's text is only "Press ", while " to continue." is stored as the tail of the b element.

INI: sections and strings, by dialect

Two widely available INI readers show how far dialects diverge.

QuestionPython configparserPHP parse_ini_file()
Value typesAlways strings; getint(), getboolean() convert on requestNormal mode turns on, yes, true into "1" and off, no, false, null into ""; typed mode yields booleans, integers and null
Comment prefixes# and ; on their own lines by default;
Key namesLowercased by defaultWords such as null, yes and true are reserved
Interpolation%(name)s by defaultConstants and ${...} in normal mode

Running the Python reader on small probes (Python 3.14.4) showed the defaults in action: port = 80 ; web returned the whole string '80 ; web' because inline comments are off; p = 50% raised InterpolationSyntaxError when the value was read; a repeated key raised DuplicateOptionError; a file with no section header raised MissingSectionHeaderError; and MyKey came back as mykey.

.env: flat strings

A .env file feeds environment variables, so every value is a string. Node.js documents its own rules: names use letters, digits and underscores and cannot start with a digit; values may be single or double quoted; quoted values may span lines; # starts a comment outside quotes; an export prefix is ignored. Docker Compose documents different details, including that an unquoted value needs a space before # for it to count as a comment, and that it interpolates unquoted and double-quoted values. The double underscore in DATABASE__HOST above is purely a naming convention.

Comment icon

Comments

All four allow comments, which separates them from strict JSON. The traps differ.

FormatTrapSurvives a parse and rewrite?
JSON5Block comments do not nestNot with a parser that returns plain data
XML-- is forbidden inside a comment, so commenting out a command-line flag breaks the fileDepends on the library; Python's default ElementTree parsing dropped it in our test
INIInline comments may be read as part of the valueconfigparser.write() does not preserve them
.envUnquoted # handling differs between loadersLoaders return only keys and values

The safe habit is the same everywhere: let people own hand-written files and let programs write to separate ones. For JSON5 specifically, see comment best practices.

Checklist icon

Schemas: XSD vs JSON Schema

XML has validation in its core: the specification defines document type definitions (DTDs) and what a validating processor does with them. XSD 1.1, a W3C Recommendation since April 5, 2012, adds a richer schema language with data types. JSON5 defines no schema language. You parse first, then validate the resulting objects with JSON Schema, whose current version is 2020-12.

<!-- XSD: validates the document --> <xs:schema xmlns:xs="http://www.w3.org/2001/XMLSchema"> <xs:element name="port"> <xs:simpleType> <xs:restriction base="xs:integer"> <xs:minInclusive value="1"/> <xs:maxInclusive value="65535"/> </xs:restriction> </xs:simpleType> </xs:element> </xs:schema>
// JSON Schema: validates the parsed value { $schema: 'https://json-schema.org/draft/2020-12/schema', type: 'object', properties: { port: { type: 'integer', minimum: 1, maximum: 65535 }, }, required: ['port'], }
AspectXSDJSON Schema with JSON5
What is checkedXML document structure and textIn-memory values after parsing
Role of the schema in typingGives text content a data typeChecks types the syntax already produced
Namespace awarenessYes, by designNot applicable

INI and .env have no standard schema. The usual approach is typed loading code that converts each key and fails loudly. For a worked setup, see schema validation.

Settings icon

Parsers You Already Have

RuntimeJSON5XMLINI.env
Python logoPythonPackage (guide)Standard libraryconfigparserPackage
Node.js logoNode.jsjson5 package (guide)PackagePackageutil.parseEnv(), --env-file
PHP logoPHPPackage (guide)XML extensionsparse_ini_file()Package

Availability is the strongest practical argument for the older formats: a Python script can read XML and INI with nothing installed. Node.js documents .env loading as a stable built-in:

node --env-file=app.env server.js node --env-file-if-exists=local.env server.js

parse_ini_file() carries a warning in the PHP manual: it must not be used on untrusted input unless the scanner mode is INI_SCANNER_RAW, because normal parsing can expose the values of constants. "Simple format" does not mean "simple parser".

Security icon

Security: XXE and Entity Expansion

An XML document type declaration can define entities, including external ones that point at a URI. When a parser resolves such an entity in untrusted input, the result is XML External Entity (XXE) injection. The OWASP prevention cheat sheet lists local file disclosure, server-side request forgery and resource exhaustion among the impacts. The XML specification lets a processor that is not validating skip the replacement text of external entities and does not oblige it to read external declarations, so behavior varies by parser and by settings.

<!-- shape of an XXE payload --> <!DOCTYPE config [ <!ENTITY secret SYSTEM "file:///path/to/private/file"> ]> <config>&secret;</config>

We probed Python 3.14.4 with its bundled Expat 2.7.5 using xml.etree.ElementTree. An internal entity was expanded (hello &who; became hello world). A reference to an external SYSTEM entity was not fetched; parsing failed with ParseError: undefined entity &x;. That result describes this parser and version only.

Entity expansion is the second risk. The "billion laughs" attack nests entities that reference each other until a tiny file expands to gigabytes; "quadratic blowup" repeats one large entity thousands of times. Python's documentation says Expat versions below 2.7.2 may be vulnerable to these and related problems, and advises checking pyexpat.EXPAT_VERSION.

Defenses

  • Reject DOCTYPE declarations when you do not need them. In Java, OWASP names the disallow-doctype-decl parser feature.
  • Otherwise disable external entities and external DTD loading, limit expansion, and keep XInclude off.
  • In PHP, do not enable LIBXML_NOENT, LIBXML_DTDLOAD or LIBXML_DTDVALID on untrusted XML without also blocking external resources.
  • In Python, OWASP recommends the defusedxml interfaces for untrusted XML. In .NET, defaults depend on the framework version, so check yours.

The other three are not automatically safe

JSON5 has no entities, includes or references, so XXE has nothing to attach to. Risks move elsewhere: never eval the text, bound input size and nesting, keep the library patched, and validate the result. INI parsers with interpolation can substitute values you did not expect. A .env file usually holds secrets, so keep it out of source control and web roots. More in the security tutorial.

Convert icon

Conversion, With Tested Code

Everything in this section was run on the four files above with Node.js 24.22.1, the json5 package 2.2.3 and Python 3.14.4. The Python scripts use only the standard library. Because JSON is valid JSON5, their JSON output can be saved directly as a .json5 file.

JSON5 to XML

npx json5 config.json5 -o config.json python json2xml.py config.json
# json2xml.py import json, sys import xml.etree.ElementTree as ET def build(parent, key, value): if isinstance(value, list): for item in value: build(parent, key, item) return el = ET.SubElement(parent, key) if isinstance(value, dict): for k, v in value.items(): build(el, k, v) elif isinstance(value, str): el.text = value else: el.text = json.dumps(value) # 8080, false, null root = ET.Element("config") with open(sys.argv[1], encoding="utf-8") as f: for k, v in json.load(f).items(): build(root, k, v) ET.indent(root) print(ET.tostring(root, encoding="unicode"))

Real output:

<config> <name>orders-api</name> <port>8080</port> <debug>false</debug> <zip>02134</zip> <owner>null</owner> <hosts>a.example.com</hosts> <hosts>b.example.com</hosts> <database> <host>db.internal</host> <timeout>2.5</timeout> </database> </config>

The comment is gone, null became the four letters "null", and an empty list would vanish. A JSON5 key can be any string, but an XML name cannot. ElementTree did not check: creating an element called my key serialized as <my key />, which is not that element and not well formed. Validate names before building the tree.

XML to JSON5

# xml2json.py - trusted input only import json, sys import xml.etree.ElementTree as ET def to_data(el): out = dict(el.attrib) # attributes become keys for child in el: out.setdefault(child.tag, []).append(to_data(child)) text = (el.text or "").strip() if not out: return text # leaf element: a string if text: out["#text"] = text # unwrap lists that hold one item return {k: v[0] if isinstance(v, list) and len(v) == 1 else v for k, v in out.items()} root = ET.parse(sys.argv[1]).getroot() print(json.dumps({root.tag: to_data(root)}, indent=2))
{ "config": { "name": "orders-api", "port": "8080", "debug": "false", "zip": "02134", "owner": "", "host": [ "a.example.com", "b.example.com" ], "database": { "host": "db.internal", "timeout": "2.5" } } }

Every value is a string, and nothing shows that name was an attribute. With one <host> the key would hold a string instead of a list, so real converters need a list of names that are always arrays. This script also ignores namespaces beyond the expanded tag names and discards text that follows child elements, so it is unsuitable for mixed content.

INI to JSON5

# ini2json.py import configparser, json, sys parser = configparser.ConfigParser(interpolation=None) with open(sys.argv[1], encoding="utf-8") as f: parser.read_file(f) print(json.dumps({s: dict(parser[s]) for s in parser.sections()}, indent=2))
{ "server": { "name": "orders-api", "port": "8080", "debug": "false", "zip": "02134", "owner": "", "hosts": "a.example.com, b.example.com" }, "database": { "host": "db.internal", "timeout": "2.5" } }

.env to JSON5, with explicit types

Never guess types from appearance: a guesser would turn 02134 into 2134. State each conversion.

// env2json5.js const fs = require('fs'); const { parseEnv } = require('util'); const JSON5 = require('json5'); const flat = parseEnv(fs.readFileSync(process.argv[2], 'utf8')); const int = (s) => { if (!/^\d+$/.test(s)) throw new Error(`not an integer: ${s}`); return Number(s); }; const bool = (s) => { if (s !== 'true' && s !== 'false') throw new Error(`not a boolean: ${s}`); return s === 'true'; }; console.log(JSON5.stringify({ name: flat.APP_NAME, port: int(flat.PORT), debug: bool(flat.DEBUG), zip: flat.ZIP, owner: flat.OWNER || null, hosts: flat.HOSTS.split(','), database: { host: flat.DATABASE__HOST, timeout: Number(flat.DATABASE__TIMEOUT), }, }, null, 2));
{ name: 'orders-api', port: 8080, debug: false, zip: '02134', owner: null, hosts: [ 'a.example.com', 'b.example.com', ], database: { host: 'db.internal', timeout: 2.5, }, }

The output matches the original data. Node.js also dropped the trailing # seconds comment, returning '2.5'. See conversion tools for more routes.

Target icon

When Each Format Wins

XML wins

  • Content is prose with inline markup
  • Independent vocabularies must share a document
  • A contract is already expressed in XSD
  • The tool you configure reads XML; matching it beats converting

INI wins

  • Settings are shallow and edited by people who should not manage braces and quotes
  • A script must run on a bare Python or PHP install
  • The consuming program already defines its INI dialect

.env wins

  • The goal is to set environment variables
  • Values differ per machine and stay out of the repository
  • Containers and process managers consume it directly

JSON5 wins

  • Settings are nested, with lists and real types
  • The program already thinks in JSON-style data
  • People need comments and trailing commas
  • You want one published grammar, not a dialect per loader

JSON5 costs you a dependency in most runtimes, has no built-in schema or namespaces, and cannot express marked-up text naturally. Those are real limits, covered further in criticism and limitations.

Combining formats is normal. A common arrangement keeps structure in a committed .json5 file and secrets in environment variables, with the program merging the two through an explicit list of keys. Compare other candidates in JSON5 vs YAML and JSON5 vs TOML.

Common Questions

Is JSON5 a replacement for XML?

For structured settings, often yes. For documents with inline markup or namespace-based vocabularies, no.

Is INI a standard?

There is no single shared specification that parsers follow. Python and PHP differ on types, comments and interpolation, so document which reader your file targets.

Can JSON5 files suffer XXE?

The grammar has no entities or external references, so there is no such mechanism. A program can still act unsafely on a URL or path it reads from any format.

Can I put JSON5 inside a .env value?

It is just a string, so you can store it and parse it yourself, and Node.js allows quoted values to span lines. A separate file is easier to review and validate.

Should XML data go in attributes or elements?

Use an element if the value may repeat, may gain structure, or contains long text. Attributes suit short, single facts about an element.