# Working with JSON and XML Data Formats

> Chapter 7 of the Courseiva CISCO-DEVNET-ASSOCIATE curriculum — https://courseiva.com/learn/cisco-devnet-associate/json-and-xml-data-formats

**Official objective:** 1.3 — Construct and parse JSON and XML payloads for API requests

## Introduction

How do two different computer programs — say, a mobile app and a web server running hundreds of miles apart — exchange information in a way both can understand?  This is the fundamental problem that data formats like JSON and XML solve: they provide a standardised, structured way to represent data so that any system, regardless of the programming language or platform it uses, can parse (read and interpret) and construct (create and send) that data reliably.  For the Cisco DevNet Associate 200-901 exam, understanding how to construct and parse JSON and XML payloads is a core skill because nearly every interaction with a REST API — the backbone of modern network automation — uses one of these two formats to transmit the actual data being requested or sent.

## The Recipe Card Analogy

A recipe card is a structured set of instructions for cooking a specific dish.  It contains clearly labelled sections: a list of ingredients with quantities, a step-by-step method, a cooking time, and a serving size.  Each section has a defined purpose, and the entire card follows a consistent format so any cook can understand it.  When you follow the recipe exactly, you reliably produce the intended meal.  However, if you try to send this recipe to a friend who only speaks a different language, you need to translate it.  JSON and XML are like two different languages for writing this same recipe card.  JSON is the concise, modern shorthand — it uses curly braces {} to group ingredients, colons to separate ingredient names from their quantities, and square brackets [] to list multiple steps.  It is lightweight and easy for both humans and computers to read quickly.  XML is the more formal, verbose language — it uses angle-bracket tags like <ingredient><name>flour</name><quantity>2 cups</quantity></ingredient> to wrap every piece of data in labelled markers.  XML is more expressive but bulkier, and it enforces a stricter structure.  Both formats can represent the exact same recipe — the same dish, the same steps, the same ingredients — but they do it with different syntax rules.  A chef (the API developer) chooses one format over the other based on the situation: JSON for speed and simplicity when building a web app, XML for complex data with lots of metadata or for legacy systems that already expect XML.  The core analogy holds: the recipe card is the data, and JSON or XML is the way you write that data down so it can be shared, read, and used reliably.

## Core explanation

When two computers talk to each other across a network, they need a common language.  Raw data — like a list of network devices, their IP addresses, and their status — has no inherent structure.  You cannot just send a string of text like 'router1 10.0.0.1 up' and expect the receiving program to know that 'router1' is the name, '10.0.0.1' is the IP address, and 'up' is the status.  JSON and XML solve this by wrapping the data in a predictable structure that both the sender and receiver understand.  This process of converting data into a structured string is called serialisation (or marshalling), and the reverse — reading that structured string back into usable data in memory — is called deserialisation (or unmarshalling).

JSON stands for JavaScript Object Notation.  Despite the 'JavaScript' in its name, JSON is language-independent — almost every programming language has a library to parse and generate JSON.  A JSON payload is built from two main structures: objects and arrays.

- An object is an unordered collection of key-value pairs, wrapped in curly braces {}.  A key is always a string in double quotes.  A value can be a string (in double quotes), a number (no quotes), a boolean (true or false, no quotes), null, an array, or another object.
- An array is an ordered list of values, wrapped in square brackets [].  Each value in the array is separated by a comma.  Values in an array do not have keys.

For example, a single network device in JSON looks like this:

{
  "hostname": "Router-1",
  "ip_address": "10.0.0.1",
  "status": "up",
  "interfaces": ["GigabitEthernet0/0", "GigabitEthernet0/1"]
}

Notice how each piece of data is labelled with a key (like "hostname") and its value follows after a colon.  The list of interfaces is an array with two string values.  This structure is intuitive and easy to read.

XML stands for eXtensible Markup Language.  It uses custom tags — similar to HTML tags — to mark up data.  Tags come in pairs: an opening tag like <hostname> and a closing tag like </hostname>.  Everything between the opening and closing tags is the value.  Tags can contain attributes inside the opening tag, like <device type="router">.  XML is more verbose than JSON because every data element requires both an opening and a closing tag.  The same network device in XML looks like this:

<device>
  <hostname>Router-1</hostname>
  <ip_address>10.0.0.1</ip_address>
  <status>up</status>
  <interfaces>
    <interface>GigabitEthernet0/0</interface>
    <interface>GigabitEthernet0/1</interface>
  </interfaces>
</device>

Both JSON and XML represent the exact same information, but JSON does it with fewer characters.  This is why JSON has become the dominant format for modern REST APIs — it is lighter, faster to transmit, and easier for humans to read.

Why does this matter for the 200-901 exam?  When you send a POST request to an API — for example, to create a new VLAN on a network switch — you must include a payload (the data body of the request) that the API can understand.  The API documentation will specify whether it expects a JSON payload or an XML payload.  Your job is to construct that payload correctly, respecting the exact key names and data types the API expects.  One wrong character — a missing comma, an extra bracket, a key name misspelled — and the API will return an error instead of completing your request.  Similarly, when you receive a response from an API, it will contain a JSON or XML payload that you must parse to extract the information you need.  You need to know how to navigate the structure, access nested objects or arrays, and convert the data into a format your program can use.

Both JSON and XML support nesting.  An object can contain another object, or an array of objects, allowing you to represent complex relationships.  For example, a JSON object representing a network could contain an array of device objects, each of which contains an array of interface objects.  Mastering this nesting is a key skill for building and parsing real-world API payloads.

## Real-world context

Imagine you work as a junior network automation engineer for a company that manages hundreds of routers and switches across three data centres.  Your manager asks you to write a script that fetches the current configuration of every device in the 'EU-West' data centre, checks whether the SNMP community string is set to the default 'public', and if so, updates it to a secure custom string.  This is a common automation task that relies entirely on constructing and parsing JSON payloads.

First, you need to get a list of devices in the EU-West data centre.  Your organisation uses a network management platform that exposes a REST API.  You send a GET request to the endpoint https://netman.example.com/api/v1/devices?location=EU-West and, in the response, you receive a JSON payload that looks like this:

{
  "count": 45,
  "devices": [
    {
      "hostname": "eu-core-router-01",
      "mgmt_ip": "192.168.1.1",
      "status": "online"
    },
    {
      "hostname": "eu-core-router-02",
      "mgmt_ip": "192.168.1.2",
      "status": "online"
    }
  ]
}

Your script parses this JSON payload.  It iterates over the "devices" array, extracting each device's hostname and management IP address.  For each device, your script then sends a second GET request to a different API endpoint specifically for that device's configuration: https://netman.example.com/api/v1/devices/eu-core-router-01/config.  The response contains a JSON payload with the full configuration.  Your script parses this payload, looking for the key "snmp_community_string".  If the value is "public", your script knows the device is vulnerable.  It then constructs a new JSON payload to update the configuration:

{
  "snmp_community_string": "secure-$2a$10$...",
  "snmp_version": "v3"
}

Your script sends a PUT or PATCH request to the same API endpoint, with this JSON payload in the request body.  If the request is successful, the API returns a 200 OK response with a JSON body confirming the change.  Your script then logs the success.

Throughout this entire workflow, the core technical actions are:

- Parsing JSON response payloads to extract lists of devices, their IPs, and configuration details.
- Constructing JSON request payloads with the exact key names (like "snmp_community_string") and value types (string, with quotes) that the API expects.
- Handling errors when the API returns a JSON error payload (e.g., {"error": "Device not found"}) and deciding how to proceed.

If you had to do this manually for 45 devices, it would take hours and be error-prone.  By writing a script that constructs and parses JSON payloads, you complete the task in seconds with perfect accuracy.  This is the power of data format manipulation in network automation — and it is exactly what the 200-901 exam tests.

## Exam focus

The 200-901 exam tests your ability to both construct and parse JSON and XML payloads.  This means you must be able to look at a correctly formatted payload, extract specific data from it, and also write a valid payload from scratch given a description of the data.  The exam uses a question format called 'drag and drop' or 'fill in the blank' where you select the correct syntax element from a list.  You will not be writing code on a keyboard, but you must recognise correct and incorrect syntax on sight.

The exam loves to test these specific concepts:

- Correct JSON syntax: double quotes on keys and string values, no trailing commas after the last element in an object or array, colon between key and value, commas between key-value pairs.  They will present payloads with single quotes, missing quotes, or extra commas, and ask you to identify the error.
- Nested object access: Given a JSON payload like {"data": {"devices": [{"name": "R1"}]}}, can you identify the correct way to access the value "R1"?  In Python, this would be data['data']['devices'][0]['name'].  In the exam, you might select the correct path from multiple choices.
- XML vs JSON comparison: They will ask which format is more verbose, which supports namespaces, which is better suited for lightweight data (JSON).  XML supports attributes on tags (e.g., <device type="router">), while JSON does not have a direct equivalent — you would use a nested object instead.
- Array indexing: Remember that JSON arrays are zero-indexed.  The first element in an array is at index 0, not 1.  This is a common trap.
- Data types: They will test that booleans and numbers in JSON are not quoted.  "active": true is correct; "active": "true" is wrong (it becomes a string).  XML does not have native data types — everything is text, so parsing must be done manually.

Traps the exam sets:

- They give you a payload with a valid structure but one key misspelled compared to the API specification.  You must spot the mismatch.
- They present a JSON array and ask you to count how many objects it contains — easy but easy to miscount if you rush.
- They show an XML payload with mismatched opening and closing tags (e.g., <hostname>...</hostname> vs <Hostname>...</Hostname> — XML is case-sensitive).  Case sensitivity in both JSON and XML is a frequent trap.
- They include a comment in the JSON payload (like /* comment */ or // comment), which is not valid JSON — comments are not allowed.  This is a classic trick.

The correct answer pattern is: always check quotes first, then commas, then bracket or tag pairing, then data types, then key names.  Practise reading payloads line by line to spot errors quickly.

## Step by step

1. **Identify the API's expected format** — Read the API documentation to determine whether the endpoint expects JSON or XML.  The documentation will specify the Content-Type header (e.g., application/json or application/xml) that must be set in your request.  Sending a JSON payload when the API expects XML will usually result in a 400 Bad Request error.
2. **Plan the data structure** — Decide what data you need to send or receive.  Draw a rough mental model: is it a single object with properties, or a list of objects?  For example, to create a new VLAN, you might need an object with keys 'vlan_id' (number), 'name' (string), and 'enabled' (boolean).  This step avoids confusion about nesting levels.
3. **Construct the payload in the correct syntax** — Write out the JSON or XML payload following the format rules.  For JSON, use curly braces for objects, square brackets for arrays, colons between keys and values, commas between pairs, and double quotes on all keys and string values.  For XML, create a root element, then add child elements with opening and closing tags for each data point.  Do not forget to close every tag.
4. **Validate the payload for syntax errors** — Before sending the request, pass the payload through a syntax validator (many online tools or IDE plugins are available).  Check for common mistakes: trailing commas, missing quotes, mismatched brackets or tags, and double-check that booleans and numbers are not quoted.  A single syntax error will cause the entire request to fail.
5. **Send the request and parse the response** — Include the constructed payload in the request body and set the correct Content-Type header.  After sending, the API will return a response.  If it is a successful response (2xx status code), parse the response payload — extract the needed values by navigating the structure using key names or tag names.  If it is an error response, parse the error payload to understand what went wrong and adjust your request accordingly.

## Comparisons

### JSON (JavaScript Object Notation) vs XML (eXtensible Markup Language)

**JSON (JavaScript Object Notation):**
- Uses curly braces {} for objects and square brackets [] for arrays.
- Supports native data types: string, number, boolean, null, object, array.
- Keys and string values must be enclosed in double quotes.

**XML (eXtensible Markup Language):**
- Uses custom opening and closing tags like <device></device> to structure data.
- All values are text — data types like numbers or booleans are not natively supported.
- Tags can include attributes inside the opening tag, e.g., <device type="router">.

### JSON Object vs JSON Array

**JSON Object:**
- Enclosed in curly braces { } and contains unordered key-value pairs.
- Keys are unique strings that label each value.
- Access values using the key name, e.g., data.hostname.

**JSON Array:**
- Enclosed in square brackets [ ] and contains an ordered list of values.
- Values do not have keys — they are accessed by their numerical index, starting at 0.
- Access values using the index, e.g., data[0] for the first element.

### Serialisation vs Deserialisation

**Serialisation:**
- The process of converting in-memory data (like a dictionary) into a JSON or XML string.
- Performed before sending data to an API in a request body.
- In Python, this is done with json.dumps() or an XML library.

**Deserialisation:**
- The process of converting a JSON or XML string back into in-memory data structures.
- Performed after receiving data from an API response.
- In Python, this is done with json.loads() or an XML parser.

### Valid JSON Payload vs Invalid JSON Payload

**Valid JSON Payload:**
- Uses double quotes on all keys and string values.
- No trailing commas after the last key-value pair or array element.
- Booleans and numbers are unquoted (e.g., true, 42).

**Invalid JSON Payload:**
- Uses single quotes anywhere in the payload.
- Contains a comma after the last element in an object or array.
- Wraps a boolean like true in double quotes: "true" (making it a string).

## Diagram

_Flowchart showing the decision between JSON and XML formats, construction, validation, API processing, and parsing of the response payload._

```mermaid
flowchart TD
    A[Data in memory] --> B{Which format?}
    B -->|JSON| C[Construct JSON payload]
    B -->|XML| D[Construct XML payload]
    C --> E[Include in HTTP request body]
    D --> E
    E --> F[Send request to API]
    F --> G[API parses payload]
    G --> H{Valid syntax?}
    H -->|Yes| I[Process data and return response]
    I --> J[Response payload in JSON/XML]
    J --> K[Client parses response]
    K --> L[Extract needed values]
    H -->|No| M[Return 400 error with error payload]
    M --> N[Client reads error and fixes payload]
```

## Common misconceptions

- **Misconception:** JSON is only for JavaScript and cannot be used by other programming languages. **Reality:** JSON is completely language-independent.  Almost every modern programming language (Python, Java, C#, Ruby, Go, etc.) has built-in or library-based support for parsing and generating JSON. (The name 'JavaScript Object Notation' strongly implies a JavaScript-only origin, leading beginners to assume it is not usable elsewhere.)
- **Misconception:** XML and JSON are interchangeable in every scenario, and you can always convert one to the other without any information loss. **Reality:** While they represent similar structured data, XML supports features like namespaces, attributes, and processing instructions that have no direct equivalent in JSON.  A conversion from XML to JSON can lose metadata embedded in attributes. (Beginners see examples of simple data in both formats and assume the correspondence is always exact, missing XML's richer structural capabilities.)
- **Misconception:** In JSON, you can use single quotes for keys and strings, just like in JavaScript. **Reality:** JSON is a strict subset of JavaScript syntax and requires double quotes for all keys and string values.  Single quotes are invalid in JSON. (Many learners come from a JavaScript background where single quotes are common, and they incorrectly transfer that habit to JSON.)
- **Misconception:** An empty JSON array [] and an empty JSON object {} are the same thing and can be used interchangeably. **Reality:** [] is an empty list (ordered sequence of values), and {} is an empty object (unordered collection of key-value pairs).  They are structurally different and are not interchangeable in API payloads. (Both appear as empty brackets or braces, so beginners think they represent the same 'nothing' concept, but they have distinct meanings in data modelling.)
- **Misconception:** When parsing a JSON payload, you can rely on the order of keys within an object staying the same. **Reality:** JSON objects are defined as unordered collections of key-value pairs.  The order of keys is not guaranteed and should never be assumed.  If order matters, use an array instead. (In many small examples, keys appear in a consistent order, leading beginners to rely on a false assumption that breaks when code encounters a different JSON source.)
- **Misconception:** XML attributes and XML child elements are essentially the same thing and can be used interchangeably. **Reality:** Attributes store simple metadata (like <device type="router">), while child elements can store complex nested data structures.  They have different parsing characteristics and are not equivalent. (Beginners see both appearing next to a parent tag and assume they serve the same purpose, not realising that elements can contain further nesting while attributes cannot.)

## Key takeaways

- JSON uses double quotes for all keys and string values, while XML uses custom opening and closing tags to wrap data.
- JSON objects are unordered collections of key-value pairs enclosed in curly braces, and JSON arrays are ordered lists of values enclosed in square brackets.
- XML tags are case-sensitive, and every opening tag must have a matching closing tag to form a valid document.
- When constructing a payload for an API, a single syntax error — like a missing comma or an extra bracket — will cause the entire request to fail with a parsing error.
- Both JSON and XML support nesting, allowing you to represent complex hierarchical data like a network of devices, each with multiple interfaces.
- To parse a payload, you must navigate the structure using the correct key names or tag names, respecting case sensitivity and data types.
- JSON is generally more lightweight and faster to transmit than XML, making it the default choice for modern REST APIs.
- Empty data in JSON is represented as null (without quotes), not as the string "null" or an empty string "".
- XML supports attributes within opening tags (e.g., <interface type="ethernet">), which JSON does not have natively — attributes are often modelled as nested objects in JSON.
- A valid JSON payload must not contain any comments, trailing commas, or unquoted key names.

## FAQ

**What is the difference between JSON and XML for REST APIs?**

JSON is more lightweight and faster to parse, making it the preferred choice for most modern REST APIs.  XML is more verbose but supports features like namespaces and attributes that are useful for complex document-oriented data, especially in legacy systems.

**Can I use comments inside a JSON payload?**

No, JSON does not support comments of any kind.  If you need to add explanatory text, consider including a separate documentation field in the payload or using a pre-processing step to strip comments before parsing.

**What happens if I send a JSON payload with single quotes?**

The API server's JSON parser will reject the payload as invalid, and the server will return a 400 Bad Request error with a message like 'Invalid JSON'.  JSON strictly requires double quotes for keys and string values.

**How do I represent a list of devices in JSON?**

Use a JSON array, which is an ordered list enclosed in square brackets.  Each device in the list would be a JSON object containing key-value pairs for the device's properties, like {"hostname": "R1", "ip": "10.0.0.1"}.

**What does 'parse' mean when talking about JSON or XML?**

Parsing means reading the structured text (the JSON or XML string) and converting it into a data structure in your programming language, such as a dictionary or object.  For example, in Python, json.loads(json_string) converts a JSON string into a Python dictionary.

**What is a 'payload' in the context of APIs?**

A payload is the actual data content sent in the body of an API request (like a POST request) or received in the response.  It is the 'package' of data that carries the information you want to send or retrieve, distinct from headers and metadata.

## Check your understanding

1. **What are the two main structural elements in a JSON payload, and what characters enclose each?**

   Answer: Objects are enclosed in curly braces {} and arrays are enclosed in square brackets [].

2. **In JSON, must keys be enclosed in single quotes or double quotes?**

   Answer: All JSON keys must be enclosed in double quotes. Single quotes are invalid in JSON.

3. **What is the primary difference between an XML attribute and an XML child element?**

   Answer: An attribute is a simple key-value pair within the opening tag (e.g., <device type="router">), while a child element is a separate opening and closing tag that can contain nested data.

4. **If you receive a JSON response and need to access the third device in an array of devices, what index would you use?**

   Answer: You would use index 2, because JSON arrays are zero-indexed, meaning the first element is at index 0, the second at index 1, and the third at index 2.

5. **What does the term 'serialisation' mean in the context of JSON and XML?**

   Answer: Serialisation is the process of converting data in memory (like a Python dictionary) into a JSON or XML string so it can be transmitted over a network.

---

Interactive version with quiz and diagrams: https://courseiva.com/learn/cisco-devnet-associate/json-and-xml-data-formats
