JSON, XML & YANG – Data Formats in Network Automation

1. Why Data Formats Matter in Network Automation

Traditional network management relied on a human reading CLI output and interpreting it visually. Automation requires machines to read, parse, and act on that same information — and machines need structured, predictable data formats to do this reliably. A show ip interface brief output is easy for a human to scan but notoriously difficult for a script to parse consistently, especially across different IOS versions where column spacing can shift.

Modern network automation protocols such as NETCONF and RESTCONF solve this by exchanging data in three well-defined formats: XML, JSON, and schemas defined by YANG models. Understanding these three components — and how they relate to each other — is essential for CCNA candidates and anyone working with programmable infrastructure.

Component Role Analogy
JSON Data encoding format — how data is represented as text The language the message is written in
XML Data encoding format — an alternative structured text representation A different language the message could be written in
YANG Data modelling language — defines what fields are valid and their types The grammar rules and vocabulary that both languages must follow
NETCONF Management protocol — transports XML-encoded YANG data over SSH The postal service that carries the letter
RESTCONF Management protocol — transports JSON or XML YANG data over HTTPS An email service that carries the letter

Related pages: NETCONF & RESTCONF Overview | Network Automation Overview | Northbound & Southbound APIs | Controller-Based Networking

2. JSON – JavaScript Object Notation

JSON (JavaScript Object Notation) is a lightweight, human-readable data interchange format. Despite its JavaScript origins, it is language-agnostic and has become the dominant encoding format for REST APIs — including RESTCONF. JSON represents data as key-value pairs organised into objects and arrays.

2.1 JSON Data Types

Data Type Syntax Example Notes
String "GigabitEthernet0/0" Always enclosed in double quotes
Number 1500 Integer or floating point; no quotes
Boolean true / false Lowercase; no quotes
Null null Represents an absent or unknown value
Object { "key": "value" } Unordered collection of key-value pairs; curly braces
Array [ "val1", "val2" ] Ordered list of values; square brackets

2.2 JSON Structure – Network Configuration Example

The following JSON object represents a router interface configuration as it might be returned by a RESTCONF GET request:

{
  "ietf-interfaces:interface": {
    "name": "GigabitEthernet0/0",
    "description": "Uplink to Core",
    "type": "iana-if-type:ethernetCsmacd",
    "enabled": true,
    "ietf-ip:ipv4": {
      "address": [
        {
          "ip": "192.168.1.1",
          "prefix-length": 24
        }
      ]
    }
  }
}

Key structural rules to remember:

Rule Detail
Keys must be strings All keys are enclosed in double quotes: "name"
Key-value pairs separated by colon "enabled": true
Pairs within an object separated by commas All pairs except the last in an object end with a comma
Objects nested inside objects The ietf-ip:ipv4 key's value is itself an object
Arrays hold lists of objects The address key holds an array of address objects, allowing multiple IP addresses on one interface
No trailing comma on last item A common syntax error — the last key-value pair in an object or last element in an array must NOT have a trailing comma

2.3 JSON in RESTCONF

When using RESTCONF, JSON is requested by setting the HTTP Accept header to application/yang-data+json. A RESTCONF GET to retrieve an interface might look like:

GET https://192.168.1.1/restconf/data/ietf-interfaces:interfaces/interface=GigabitEthernet0%2F0
Accept: application/yang-data+json
Authorization: Basic <base64-credentials>

The device responds with a JSON body validated against the relevant YANG model — in this case ietf-interfaces (RFC 8343).

3. XML – Extensible Markup Language

XML (Extensible Markup Language) is a tag-based data format that represents structured data using nested elements with opening and closing tags. XML predates JSON and is the native encoding format for NETCONF. While more verbose than JSON, XML's strict hierarchical structure and mature tooling (XPath, XSLT, XML Schema) make it well suited to complex configuration management operations.

3.1 XML Syntax Rules

Rule Example
Every element has an opening and closing tag <name>GigabitEthernet0/0</name>
Tags are case-sensitive <Name> and <name> are different elements
Elements can be nested A child element must close before its parent closes
Self-closing tag for empty elements <shutdown/> is equivalent to <shutdown></shutdown>
Attributes inside opening tags <interface type="ethernet">
XML declaration (optional but recommended) <?xml version="1.0" encoding="UTF-8"?>
Namespace declarations xmlns="urn:ietf:params:xml:ns:netconf:base:1.0" — prevents element name collisions between different YANG modules

3.2 XML Structure – Same Interface Configuration

The same router interface configuration from Section 2.2, now encoded in XML as it would appear inside a NETCONF <edit-config> RPC:

<?xml version="1.0" encoding="UTF-8"?>
<rpc xmlns="urn:ietf:params:xml:ns:netconf:base:1.0" message-id="101">
  <edit-config>
    <target>
      <running/>
    </target>
    <config>
      <interfaces xmlns="urn:ietf:params:xml:ns:yang:ietf-interfaces">
        <interface>
          <name>GigabitEthernet0/0</name>
          <description>Uplink to Core</description>
          <enabled>true</enabled>
          <ipv4 xmlns="urn:ietf:params:xml:ns:yang:ietf-ip">
            <address>
              <ip>192.168.1.1</ip>
              <prefix-length>24</prefix-length>
            </address>
          </ipv4>
        </interface>
      </interfaces>
    </config>
  </edit-config>
</rpc>

3.3 XML in NETCONF

NETCONF wraps all operations — <get>, <get-config>, <edit-config>, <copy-config>, <delete-config>, <commit> — inside XML RPC (Remote Procedure Call) envelopes. The device responds with an <rpc-reply> element containing either the requested data or an <ok/> confirmation. NETCONF sessions run over SSH (port 830) and always use XML encoding exclusively.

4. JSON vs XML – Direct Comparison

Attribute JSON XML
Verbosity Compact — less text for same data More verbose — opening and closing tags for every element
Human readability Generally considered easier to read at a glance Readable but bulkier; harder to scan in large payloads
Native protocol RESTCONF (HTTP/HTTPS) NETCONF (SSH port 830)
Comment support No native comment syntax Supports comments: <!-- comment -->
Namespace support Via YANG module prefixes in key names (e.g., "ietf-ip:ipv4") Full XML namespace support via xmlns attributes
Array representation Native: [ ] syntax Repeated sibling elements imply a list
Attribute metadata No concept of attributes — everything is a key-value pair Elements can have attributes providing metadata without nesting
Parser availability Native in JavaScript, Python (json module), all modern languages Available everywhere but requires more complex parsing libraries
YANG encoding standard RFC 7951 RFC 7950 (YANG 1.1), RFC 6020 (YANG 1.0)

5. YANG – Yet Another Next Generation

YANG (Yet Another Next Generation) is a data modelling language defined in RFC 6020 (YANG 1.0) and updated by RFC 7950 (YANG 1.1). YANG does not carry configuration data itself — instead, it defines the structure, syntax, and constraints that configuration data must conform to. Think of YANG as the schema or blueprint; JSON and XML are the actual data encoded according to that blueprint.

A YANG model answers questions like: what configuration nodes does this device support? What data type is each field? Which fields are mandatory? What are the valid value ranges? When a NETCONF or RESTCONF client sends data to a device, the device validates that data against the loaded YANG models before applying it — preventing misconfiguration at the protocol level.

5.1 YANG Building Blocks

YANG Statement Purpose Example
module Top-level container; names the YANG module module ietf-interfaces { ... }
container Groups related nodes; maps to a JSON object or XML element container interfaces { ... }
list Defines a list of entries identified by a key; maps to JSON array or repeated XML elements list interface { key "name"; ... }
leaf A single scalar value (string, integer, boolean, etc.) leaf name { type string; }
leaf-list A list of scalar values of the same type leaf-list dns-server { type inet:ip-address; }
type Constrains the data type of a leaf type uint16; — unsigned 16-bit integer
mandatory Declares a leaf as required mandatory true;
default Specifies a default value when the leaf is absent default "true";
description Human-readable documentation embedded in the model description "The name of the interface.";
uses / grouping Reusable node groups — define once, reference many times grouping address { leaf ip { ... } }
augment Extends another module's schema without modifying the original Cisco vendor models augment IETF base models
rpc Defines an operation (like a function call) the device supports rpc commit { ... }
notification Defines an event the device can send to a subscriber notification interface-state-change { ... }

5.2 A Simplified YANG Module Example

The following is a simplified (not production) YANG snippet illustrating how an interface list might be modelled:

module example-interfaces {
  namespace "http://example.com/ns/interfaces";
  prefix "ex-if";

  import ietf-inet-types {
    prefix inet;
  }

  container interfaces {
    description "Top-level container for interface configuration.";

    list interface {
      key "name";
      description "A list of network interfaces.";

      leaf name {
        type string;
        mandatory true;
        description "The interface name, e.g. GigabitEthernet0/0";
      }

      leaf description {
        type string;
        description "A human-readable description.";
      }

      leaf enabled {
        type boolean;
        default "true";
        description "Whether the interface is administratively enabled.";
      }

      leaf mtu {
        type uint16 {
          range "64..9216";
        }
        default "1500";
        description "The MTU in bytes.";
      }

      leaf ip-address {
        type inet:ipv4-address;
        description "The IPv4 address assigned to the interface.";
      }

      leaf prefix-length {
        type uint8 {
          range "0..32";
        }
        description "The IPv4 prefix length (subnet mask bits).";
      }
    }
  }
}

Notice how the YANG model enforces constraints: the mtu leaf is constrained to the range 64–9216, and prefix-length is constrained to 0–32. Any NETCONF or RESTCONF payload that violates these constraints will be rejected by the device with a validation error before the configuration is ever applied.

6. YANG Model Sources – IETF, OpenConfig, and Vendor

Multiple organisations publish YANG models. Understanding who publishes what — and why that matters — is important for working with programmable devices in heterogeneous environments.

Model Source Examples Characteristics
IETF ietf-interfaces (RFC 8343), ietf-ip (RFC 8344), ietf-routing (RFC 8349) Standards-based; vendor-neutral; designed for interoperability across all compliant devices. Coverage is broad but sometimes lacks vendor-specific features
OpenConfig openconfig-interfaces, openconfig-bgp, openconfig-ospf Vendor-neutral; developed by a consortium of network operators (Google, Microsoft, AT&T, etc.). More opinionated and feature-rich than IETF models; widely supported on modern platforms
Cisco (vendor-native) Cisco-IOS-XE-native, Cisco-IOS-XE-mpls Cisco-specific models that expose the full feature set of IOS-XE, including proprietary features not covered by IETF or OpenConfig. Not portable to non-Cisco devices

In practice, a RESTCONF client querying a Cisco IOS-XE device can use any of these model namespaces depending on which feature it is configuring. IETF and OpenConfig models are preferred for multi-vendor automation scripts; vendor-native models are used when the feature is Cisco-specific.

Related pages: RESTCONF Basics Lab | NETCONF & RESTCONF Overview | NETCONF with Python (ncclient) Lab

7. How JSON, XML, and YANG Work Together with NETCONF and RESTCONF

The relationship between these components follows a clear layered model: YANG defines what is valid, JSON/XML encodes the actual data, and NETCONF/RESTCONF transports that encoded data between the management application and the network device.

Layer NETCONF Stack RESTCONF Stack
Transport SSH (port 830) HTTPS (port 443)
Protocol NETCONF (RFC 6241) RESTCONF (RFC 8040)
Encoding XML only JSON (application/yang-data+json) or XML (application/yang-data+xml)
Data Schema YANG models YANG models
Operations get, get-config, edit-config, copy-config, delete-config, lock, unlock, commit, close-session HTTP GET, POST, PUT, PATCH, DELETE (maps to CRUD operations)
Datastore support running, startup, candidate (full datastore management) running and startup (limited datastore model)
Transactions Full atomic transactions with candidate datastore and commit/rollback Simpler; each operation is immediately applied

7.1 RESTCONF Workflow – Reading an Interface (JSON)

# Step 1 — GET request using Python requests library
import requests
import json

url = "https://192.168.1.1/restconf/data/ietf-interfaces:interfaces/interface=GigabitEthernet0%2F0"
headers = {
    "Accept": "application/yang-data+json",
    "Content-Type": "application/yang-data+json"
}
response = requests.get(url, headers=headers, auth=("admin", "cisco123"), verify=False)

# Step 2 — Parse JSON response
data = response.json()
iface = data["ietf-interfaces:interface"]
print(f"Interface: {iface['name']}")
print(f"Description: {iface.get('description', 'None')}")
print(f"Enabled: {iface['enabled']}")

7.2 NETCONF Workflow – Editing Configuration (XML)

# Using ncclient Python library to send a NETCONF edit-config
from ncclient import manager

edit_payload = """
<config>
  <interfaces xmlns="urn:ietf:params:xml:ns:yang:ietf-interfaces">
    <interface>
      <name>GigabitEthernet0/1</name>
      <description>Link to Distribution</description>
      <enabled>true</enabled>
    </interface>
  </interfaces>
</config>
"""

with manager.connect(
    host="192.168.1.1",
    port=830,
    username="admin",
    password="cisco123",
    hostkey_verify=False
) as m:
    response = m.edit_config(target="running", config=edit_payload)
    print(response)  # <rpc-reply><ok/></rpc-reply> on success

Related pages: RESTCONF Basics Lab | NETCONF with Python Lab | Python for Networking

8. YANG Tools and Exploration

Several tools help engineers explore YANG models and validate data against them without needing a physical device.

Tool Purpose Notes
pyang Python YANG validator and formatter; can render models as trees pyang -f tree ietf-interfaces.yang — displays the model hierarchy visually
yanglint Validates YANG modules and data instances against models Part of the libyang library; used to check that JSON/XML payloads are schema-valid before sending to a device
YANG Catalog Online repository of published YANG models from IETF, OpenConfig, and vendors Available at yangcatalog.org — searchable by module name
Cisco YANG Suite GUI tool for browsing Cisco YANG models, building NETCONF/RESTCONF requests, and testing against live devices Runs as a Docker container; available from Cisco DevNet
Postman GUI HTTP client for testing RESTCONF requests manually Ideal for exploring RESTCONF endpoints before scripting; see Ansible Overview
ncclient Python library for NETCONF session management See NETCONF with Python Lab for full configuration examples

9. Quick Reference – JSON, XML & YANG at a Glance

Topic Key Fact
JSON delimiter for objects Curly braces { }
JSON delimiter for arrays Square brackets [ ]
JSON string quoting Double quotes only — "value"
XML element structure Opening tag + content + closing tag: <tag>data</tag>
XML namespace attribute xmlns="..." in the opening tag
NETCONF encoding XML only (SSH port 830)
RESTCONF encoding JSON or XML (HTTPS port 443)
YANG leaf Single scalar value with a defined type
YANG list Multiple entries identified by a key — maps to JSON array
YANG container Groups related nodes — maps to JSON object / XML element
IETF model source Standards-based; vendor-neutral (e.g., ietf-interfaces RFC 8343)
OpenConfig model source Operator-consortium; vendor-neutral; richer feature coverage
Vendor-native model Device-specific full feature coverage; not portable
YANG RFC (1.0 / 1.1) RFC 6020 (YANG 1.0) / RFC 7950 (YANG 1.1)

Related pages: Network Automation Overview | NETCONF & RESTCONF Overview | Northbound & Southbound APIs | Ansible Overview | Python for Networking | Jinja2 Config Generation Lab

Practice Quiz – JSON, XML & YANG

1. In a JSON object, how must all key names be formatted?

Correct answer is C. JSON requires all key names to be enclosed in double quotes. This is one of the most strictly enforced JSON syntax rules — single quotes are not valid JSON (they are valid in JavaScript but not in strict JSON per RFC 8259). Unquoted keys are also invalid JSON. Angle-bracket tags describe XML syntax, not JSON. A JSON parser will reject a document with single-quoted or unquoted keys.

2. Which protocol uses XML as its exclusive encoding format and operates over SSH on port 830?

Correct answer is B. NETCONF (RFC 6241) uses XML as its only encoding format and operates over SSH on TCP port 830. RESTCONF (RFC 8040) uses HTTPS and supports both JSON and XML encoding. SNMP uses its own binary encoding (BER/DER) over UDP, not XML. This distinction between NETCONF (XML/SSH/830) and RESTCONF (JSON or XML / HTTPS / 443) is a common CCNA exam question.

3. What is the primary role of a YANG model in network automation?

Correct answer is D. YANG is a data modelling language, not a transport protocol or encoding format. It defines what data nodes a device supports, what type each node must be, which fields are mandatory, and what value ranges are valid. JSON and XML are encoding formats that carry actual data — YANG is the schema that describes what that data must look like. Think of YANG as the grammar rules and JSON/XML as the language. NETCONF and RESTCONF validate all incoming data against the loaded YANG models before applying it.

4. In a YANG model, what is the difference between a leaf and a list?

Correct answer is A. A YANG leaf is a single scalar value — for example, the name of an interface (a string) or whether it is enabled (a boolean). A YANG list is a collection of entries where each entry is identified by one or more key leaves — for example, a list of interfaces where each entry is identified by its name. In JSON, a YANG list maps to an array of objects. In XML, it maps to repeated sibling elements with the same tag name.

5. An engineer wants to automate BGP configuration across routers from multiple vendors using a single Python script. Which YANG model source is most appropriate and why?

Correct answer is C. OpenConfig publishes vendor-neutral YANG models for common network features including BGP (openconfig-bgp), and these models are implemented by multiple vendors (Cisco, Juniper, Arista, Nokia). A script using the OpenConfig BGP model can configure BGP on any device that supports it without rewriting for each vendor. Cisco-IOS-XE-native models are Cisco-specific and not portable. IETF models are also vendor-neutral but OpenConfig BGP models are more comprehensive and more widely adopted for this use case.

6. A RESTCONF client sends a GET request with the header Accept: application/yang-data+json. What does this header instruct the server to do?

Correct answer is B. The HTTP Accept header tells the server what encoding format the client wants in the response. The media type application/yang-data+json requests JSON encoding of YANG-modelled data. The alternative is application/yang-data+xml for XML encoding. RESTCONF supports both; the client chooses. This is a standard HTTP content negotiation mechanism applied to RESTCONF.

7. Which of the following is a valid JSON syntax error?

Correct answer is D. A trailing comma after the last key-value pair in a JSON object (or the last element in an array) is a syntax error in strict JSON (RFC 8259). Many programming languages allow trailing commas in their own object/array syntax, but JSON parsers will reject them. Options A, B, and C are all valid JSON: booleans are unquoted lowercase true, numbers are unquoted, and arrays use square brackets. The trailing comma is one of the most common mistakes when writing JSON by hand.

8. What is the purpose of the augment statement in YANG?

Correct answer is A. The YANG augment statement allows one module to insert new nodes into the schema tree defined by another module. This is how Cisco vendor-native models can extend the standard IETF ietf-interfaces model with Cisco-specific leaves (such as Cisco-proprietary QoS bindings on an interface) without altering the original IETF model. It promotes extensibility and modularity. Option C describes grouping + uses, which is YANG's mechanism for reusable node sets.

← Back to Home