Skip to content

JSON

A short introduction to basic JSON in Python.

What is JSON?

It's a data interchange format that is widely used in programming, and typically in REST APIs. JSON is a text format that is completely language independent but uses conventions that are familiar to programmers of the C-family of languages, including C, C++, C#, Java, JavaScript, Perl, Python, and many others. These properties make JSON an ideal data interchange language.

Official JSON specification.

JSON in Python

Python has a built-in package called json, which can be used to work with JSON data.

JSON functions in Python

  • json.dumps() - converts a Python object into a JSON string. (short for "dump string")
  • json.loads() - converts a JSON string into a Python object. (short for "load string")
  • json.dump() - writes a Python object to a file in JSON format.
  • json.load() - reads a JSON file and converts it into a Python object.
Converting Python object to JSON string
import json

# some data
payload = {
    'device': 'switch1',
    'interfaces': [
        {'name': 'eth0', 'vlan': 10},
        {'name': 'eth1', 'vlan': 20},
        {'name': 'eth2', 'vlan': 30},
    ],
}

json_data = json.dumps(payload)

print(json_data)
print(type(json_data))


Output
{"device": "switch1", "interfaces": [{"name": "eth0", "vlan": 10}, {"name": "eth1", "vlan": 20}, {"name": "eth2", "vlan": 30}]}
<class 'str'>

As we can see from the output, the json.dumps() function converts a Python object into a JSON string. The resulting JSON string is a standard string, which can be printed or saved to a file. You might have have noticed the double quotes around the keys and values in the JSON string. This is a standard JSON format and is required for JSON to be valid, unlike Python strings where single quotes are also valid. Another difference between Python and JSON is boolean values. In Python, we use True and False, while in JSON, we use true and false. You can see the complete list of data types in JSON and their Python equivalents in the table.

Data types in JSON and their Python equivalents

JSON Python Example JSON Example Python
object dict {"key": "value"} {'key': 'value'}
array list ["value1", "value2"] ['value1', 'value2']
string str "value" 'value'
number int, float 123 123
bool bool true True
No value No value null None
Converting JSON string to Python object
import json

# JSON data string
json_data = '{"device": "switch1", "interfaces": [{"name": "eth0", "vlan": 10}, {"name": "eth1", "vlan": 20}, {"name": "eth2", "vlan": 30}]}'

payload = json.loads(json_data)

print(payload["device"])
print(payload["interfaces"][0])
Output
switch1
{'name': 'eth0', 'vlan': 10}

Next up: we will see how to read and write JSON data to and from a file. Jump to the next section to learn more.