# JSON5 vs XML, INI and .env: Config Compared | JSON5.dev


Source: https://json5.dev/compare/xml/

---

# 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](https://json5.dev/img/hero/compare-xml.png)

**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.

[At a Glance](#glance) [Same Config](#same-config) [Data Models](#data-model) [Comments](#comments) [Schemas](#schemas) [Parsers](#parsers) [Security and XXE](#security) [Conversion](#conversion) [When Each Wins](#when) [FAQ](#faq)

![Table icon](https://json5.dev/images/icons/table.png)

## At a Glance

Property

JSON5

XML 1.0

INI

.env

Governing document

[1.0.0 specification](https://json5.dev/spec/)

W3C Recommendation

None shared; each parser sets rules

None shared; each loader sets rules

Structure

Objects and arrays

Element tree

Sections of keys

Flat keys

Nesting

Any depth

Any depth

Convention only

Convention only

Value types

String, number, boolean, null, object, array

Text, unless a schema assigns types

Strings; some parsers convert

Strings

Comments

`//` and `/* */`

`<!-- -->`

`;` or `#`, by parser

`#`

Mixed text and markup

![No](https://json5.dev/images/icons/no.png)

![Yes](https://json5.dev/images/icons/yes.png)

![No](https://json5.dev/images/icons/no.png)

![No](https://json5.dev/images/icons/no.png)

Schema language

JSON Schema, on parsed data

DTD, XSD and others

None standard

None standard

"None shared" is the most consequential cell. XML 1.0 (Fifth Edition, November 26, 2008) and [JSON5 1.0.0](https://json5.dev/spec/) (March 2018) each say what a [conforming parser](https://json5.dev/glossary/#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](https://json5.dev/images/icons/code-file.png)

## The Same Config in All Four

The settings include the awkward cases on purpose: a number, a boolean, a postal code with a [leading](https://json5.dev/glossary/#leading-decimal-point) 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](https://json5.dev/images/icons/structure.png)

## 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](https://json5.dev/spec/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:

Behavior

Attribute

Child element

May repeat

No: a name appears once per tag

Yes

Order significant to the XML specification

No

Preserved as document structure

Can contain further structure

No

Yes

Takes the default namespace

No

Yes

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](https://www.w3.org/TR/xml-names/) (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.

Question

Python `configparser`

PHP `parse_ini_file()`

Value types

Always strings; `getint()`, `getboolean()` convert on request

Normal 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 names

Lowercased by default

Words such as `null`, `yes` and `true` are reserved

Interpolation

`%(name)s` by default

Constants 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](https://json5.dev/images/icons/comment.png)

## Comments

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

Format

Trap

Survives a parse and rewrite?

JSON5

Block comments do not nest

Not with a parser that returns plain data

XML

`--` is forbidden inside a comment, so commenting out a command-line flag breaks the file

Depends on the library; Python's default ElementTree parsing dropped it in our test

INI

Inline comments may be read as part of the value

`configparser.write()` does not preserve them

.env

Unquoted `#` handling differs between loaders

Loaders 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](https://json5.dev/tutorials/comments-best-practices/).

![Checklist icon](https://json5.dev/images/icons/checklist.png)

## 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](https://www.w3.org/TR/xmlschema11-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](https://json-schema.org/specification), 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'], }`

Aspect

XSD

JSON Schema with JSON5

What is checked

XML document structure and text

In-memory values after parsing

Role of the schema in typing

Gives text content a data type

Checks types the syntax already produced

Namespace awareness

Yes, by design

Not 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](https://json5.dev/tutorials/schema-validation/).

![Settings icon](https://json5.dev/images/icons/settings.png)

## Parsers You Already Have

Runtime

JSON5

XML

INI

.env

![Python logo](https://json5.dev/images/tech/python.png)Python

Package ([guide](https://json5.dev/python/))

Standard library

`configparser`

Package

![Node.js logo](https://json5.dev/images/tech/nodejs.png)Node.js

`json5` package ([guide](https://json5.dev/nodejs/))

Package

Package

`util.parseEnv()`, `--env-file`

![PHP logo](https://json5.dev/images/tech/php.svg)PHP

Package ([guide](https://json5.dev/php/))

XML extensions

`parse_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](https://json5.dev/images/icons/security.png)

## 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](https://cheatsheetseries.owasp.org/cheatsheets/XML_External_Entity_Prevention_Cheat_Sheet.html) 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](https://json5.dev/tutorials/security/).

![Convert icon](https://json5.dev/images/icons/convert.png)

## 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](https://json5.dev/tools/conversion/) for more routes.

![Target icon](https://json5.dev/images/icons/target.png)

## 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](https://json5.dev/criticism/).

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](https://json5.dev/compare/yaml/) and [JSON5 vs TOML](https://json5.dev/compare/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.

## Related Pages

[![Compare icon](https://json5.dev/images/icons/compare.png)

### All Comparisons

The format overview

](https://json5.dev/compare/)[![Layers icon](https://json5.dev/images/icons/layers.png)

### JSON5 vs HOCON

Another configuration format

](https://json5.dev/compare/hocon/)[![Settings icon](https://json5.dev/images/icons/settings.png)

### Config Guides

Where the format fits in tooling

](https://json5.dev/config/)

## Sources

(11)

1.  [The JSON5 Data Interchange Format 1.0.0](https://spec.json5.org/)
2.  [W3C: Extensible Markup Language (XML) 1.0, Fifth Edition](https://www.w3.org/TR/xml/)
3.  [W3C: Namespaces in XML 1.0, Third Edition](https://www.w3.org/TR/xml-names/)
4.  [W3C: XML Schema Definition Language 1.1, Part 1](https://www.w3.org/TR/xmlschema11-1/)
5.  [JSON Schema: Specification](https://json-schema.org/specification)
6.  [OWASP: XML External Entity Prevention Cheat Sheet](https://cheatsheetseries.owasp.org/cheatsheets/XML_External_Entity_Prevention_Cheat_Sheet.html)
7.  [Python documentation: XML processing modules and XML security](https://docs.python.org/3/library/xml.html)
8.  [Python documentation: configparser](https://docs.python.org/3/library/configparser.html)
9.  [PHP Manual: parse\_ini\_file](https://www.php.net/manual/en/function.parse-ini-file.php)
10.  [Node.js 24: Environment variables and .env files](https://nodejs.org/docs/latest-v24.x/api/environment_variables.html)
11.  [Docker Compose: Interpolation and .env file syntax](https://docs.docker.com/compose/how-tos/environment-variables/variable-interpolation/)

Last reviewed: November 29, 2026.
