Automation and Artificial Intelligence · Topic 2 of 7
Constructing Valid JSON
Learn the rules of valid JSON for network automation: objects, arrays, strings, numbers, booleans, null, nesting, common errors and Python handling.
- 5 min
- JSON objects use braces, and arrays use square brackets.
- Keys are strings in double quotes.
- Booleans are
trueandfalse, and null isnull, all in lower case.
What it is
JSON is a text format for structured data, and almost every network API uses it.
The name stands for JavaScript Object Notation, but it is used by every language. A JSON document holds named values and lists of values, and it is easy for people and programs to read. The exam asks you to write valid JSON and to spot errors in JSON that is almost right.
How it works
JSON has a small set of rules, and every rule is strict.
The building blocks
| Item | Written as | Example |
|---|---|---|
| Object | Braces holding key and value pairs | {"name": "R1"} |
| Array | Square brackets holding values | ["Gi1", "Gi2"] |
| String | Double quotes | "R1" |
| Number | Digits, with no quotes | 65001 or 0.5 |
| Boolean | true or false, in lower case | true |
| Null | null, in lower case | null |
The rules
- Keys must be strings in double quotes. Single quotes are not valid.
- A colon separates a key from its value, and a comma separates items.
- There is no trailing comma after the last item.
- There are no comments.
- Values can be strings, numbers, booleans, null, objects or arrays.
- Booleans and null are lower case, unlike Python's
TrueandNone. - Whitespace and line breaks outside strings do not matter, so the layout is for people.
A valid example
{
"hostname": "R1",
"asn": 65001,
"bgp_enabled": true,
"last_error": null,
"interfaces": [
{
"name": "GigabitEthernet1",
"ip": "10.1.1.1",
"mask": "255.255.255.0",
"enabled": true
},
{
"name": "GigabitEthernet2",
"ip": "10.1.2.1",
"mask": "255.255.255.0",
"enabled": false
}
]
}
The top level is an object. It holds a string, a number, two simple values, and an array of two objects. Objects can be nested inside objects and inside arrays, to any depth.
Reading nested data
To reach a value, follow the keys and the positions. In Python, once the text is loaded into a dictionary called data:
print(data["hostname"]) # R1
print(data["interfaces"][0]["name"]) # GigabitEthernet1
print(data["interfaces"][1]["enabled"]) # False
Arrays count from 0, so [0] is the first interface. Note that Python prints the JSON false as False.
Common errors
| Error | Example | Fix |
|---|---|---|
| Single quotes | {'name': 'R1'} | Use double quotes |
| Trailing comma | {"a": 1, "b": 2,} | Remove the last comma |
| Missing comma | {"a": 1 "b": 2} | Add a comma between items |
| Unquoted key | {name: "R1"} | Quote the key |
| Capital boolean | {"up": True} | Use true |
| Comment | {"a": 1} // note | Remove the comment |
| Number in quotes | {"asn": "65001"} | Valid, but it is a string, not a number |
The last row is valid JSON, but it changes the data type. An API may expect a number and reject a string.
Python and JSON
The json library moves between text and Python objects.
import json
device = {"hostname": "R1", "asn": 65001, "bgp_enabled": True}
text = json.dumps(device, indent=2)
print(text)
with open("device.json", "w") as f:
json.dump(device, f, indent=2)
with open("device.json") as f:
loaded = json.load(f)
print(loaded["asn"])
The difference between the functions is small but important. dumps and loads work with strings, and dump and load work with files. The option indent=2 makes the text easy to read.
Python's True becomes JSON true, and None becomes null. A tuple becomes an array.
Building a payload for an API
A request that creates or changes something needs a body in JSON, and a header that says so.
payload = {
"name": "Loopback100",
"description": "Test loopback",
"enabled": True,
"type": "iana-if-type:softwareLoopback"
}
headers = {"Content-Type": "application/yang-data+json"}
The header must match the format of the body. If the body is JSON and the header says XML, the server rejects the request.
Checking your JSON
Pass the text to json.loads. If it is not valid, Python raises an error that names the position of the problem. Many editors and online checkers do the same.
What to remember for the exam
Eight facts cover most questions on this topic.
- JSON objects use braces, and arrays use square brackets.
- Keys are strings in double quotes.
- Booleans are
trueandfalse, and null isnull, all in lower case. - A trailing comma is not allowed.
- JSON has no comments.
- Arrays are counted from 0 when you read them in a script.
json.loadsreads a string, andjson.loadreads a file.json.dumpswrites a string, andjson.dumpwrites a file.
When you must find the error in a JSON sample, check quotes, commas and the case of true, false and null first. Those cause most faults.
Common mistakes
These four mistakes appear often.
Using single quotes. JSON allows only double quotes.
Leaving a trailing comma. The parser rejects the last item followed by a comma.
Writing Python values. True and None are not valid JSON.
Putting numbers in quotes. The value becomes a string, and a strict API may reject it.
A JSON file that looks correct can still fail if one comma is missing, so check the text with a parser.
Check yourself
Work through these three questions.
Why is
{"a": 1, "b": 2,}invalid JSON?It has a trailing comma after the last item, which JSON does not allow.
How is the Python value
Truewritten in JSON?As
true, in lower case.What is the difference between
json.dumpsandjson.dump?dumpsreturns a string, anddumpwrites to a file.
Topic 2 of 7 in Automation and Artificial Intelligence
Test yourself on Automation and Artificial Intelligence
The full Cisco CCNP 350-401 ENCOR question bank has 854 questions, with timed practice exams and an explanation for every answer.
This study guide is independent and is not affiliated with, endorsed by, or sponsored by Cisco. Vendor names, certification names and exam codes are trademarks of their respective owners and are used for identification only.