Member-only story
How to Make JSON and Python Talk to Each Other
Processing and creating JSON data in Python
JavaScript Object Notation (JSON) is a popular data format that is commonly used in data interchanges between different systems. For instance, many APIs return results in the format of JSON data. Given JSON’s remarkable readability and its object-like structure, it’s useful to know how Python handles JSON data. In this article, we’ll see what JSON is and how to process it with the built-in json
module in Python.
JSON’s Data Structure
JSON data are structured as JSON objects, which hold data in the form of key-value pairs, just like Python dictionaries. The following code snippet shows you what a typical JSON object looks like.
{ "firstName": "John", "lastName": "Smith", "age": 35, "city": "San Francisco"}
In essence, a JSON object is scoped by a pair of curly braces, in which key-value pairs are stored. JSON objects require their keys to be only strings and this requirement allows the standard communication between different systems. The values shown include strings and integers, but JSON does support other data types, including booleans, arrays, and objects.
- String: string literals enclosed with double quotes
- Number: number literals, including integers and decimals
- Boolean: Boolean values, true or false
- Array: a list of supported data types
- Object: key-value pairs enclosed by curly braces
- Null: an empty value (null) for any valid data type
Among these types, one special attention to pay is that, unlike Python strings which can use either single or double quotes, JSON strings are enclosed only by double quotes. Improper use of single quotes invalidates JSON data, which can’t be processed by a common JSON parser.
Besides these supported data types, it’s important to know that JSON supports nested data structures. For instance, you can embed a JSON object inside another object. For another instance, an array can consist of…