Octet

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

JSON
{
  "vlans": [
    {"id": 10, "name": "USERS"},
    {"id": 20, "name": "VOICE"}
  ]
}
YAML
# VLANs for building A
vlans:
  - id: 10
    name: USERS
  - id: 20
    name: VOICE
Output
<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

JSONYAMLXML
CommentsNoYes (#)Yes (<!-- -->)
Structure byBraces and bracketsIndentation (spaces only)Opening and closing tags
Typesstring, number, true/false, null, object, arraySame plus dates and more, inferredEverything is text unless a schema says otherwise
NamespacesNo (RESTCONF uses module: prefixes)NoYes
Pythonjson (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.

Traps

  • Calling YAML a programming language. It is a data format; logic lives in Ansible, Python or Jinja2.
  • Using yaml.load without a safe loader on untrusted input. Use yaml.safe_load.
How did you do?Book 7.1 Presentation Formatting