Compare JSON, YAML and XML. Where do you meet each one in network automation?
Show the answer
Say this first
All three describe the same kinds of structured data: objects or mappings, lists and values. JSON is compact and strict, with no comments; it is the default for REST APIs, RESTCONF and gNMI. YAML is the human-friendly one, with indentation and comments; Ansible playbooks, inventories, CI pipelines and data files use it. XML is verbose but has namespaces and schemas; NETCONF uses it, and Junos can show any config or command output as XML.
Go deeper
The same data three ways
{
"vlans": [
{"id": 10, "name": "USERS"},
{"id": 20, "name": "VOICE"}
]
}# VLANs for building A
vlans:
- id: 10
name: USERS
- id: 20
name: VOICE<vlans xmlns="urn:example:vlans">
<vlan><id>10</id><name>USERS</name></vlan>
<vlan><id>20</id><name>VOICE</name></vlan>
</vlans>Differences that come up
| JSON | YAML | XML | |
|---|---|---|---|
| Comments | No | Yes (#) | Yes (<!-- -->) |
| Structure by | Braces and brackets | Indentation (spaces only) | Opening and closing tags |
| Types | string, number, true/false, null, object, array | Same plus dates and more, inferred | Everything is text unless a schema says otherwise |
| Namespaces | No (RESTCONF uses module: prefixes) | No | Yes |
| Python | json (standard library) | yaml.safe_load (PyYAML) | xml.etree.ElementTree, lxml, xmltodict |
YAML 1.2 is a superset of JSON, so a JSON document is almost always valid YAML.
They will ask next
What YAML mistakes have bitten you?
- Tabs. YAML indentation must be spaces.
- Version numbers:
version: 1.10loads as the float 1.1. Quote it. - YAML 1.1 parsers such as PyYAML (which Ansible uses) read
yes,no,onandoffas booleans, so a country codeNObecomesfalse. - The same parsers read an unquoted
22:30as a base-60 integer (1350), which also hits some MAC-like strings. - Leading zeros:
010can load as an octal number. Quote anything that is really a string.
Why does NETCONF use XML and not JSON?
NETCONF predates RESTCONF and JSON's popularity, and XML namespaces let one document mix data from several YANG modules without name clashes. RESTCONF added JSON later and solved the same problem with
module-name:prefixes on member names (RFC 7951).
Traps
- Calling YAML a programming language. It is a data format; logic lives in Ansible, Python or Jinja2.
- Using
yaml.loadwithout a safe loader on untrusted input. Useyaml.safe_load.