So far in this course, we've studied intensively two forms of information representation: relational databases, which are collections of tables; and XML, where we have trees of nodes, including elements with attributes and text.
But there are other choices for structured data. One of these is JSON: JavaScript Object Notation. Although it comes from JavaScript, it is also usable through libraries in many other programming languages.
A JavaScript object is like a Python dictionary: a collection of name-value pairs.
{"name": "Micky", "breed": "mouse", "weight": 0.2,
"sex": "male", "price": 1025.00}
Names are strings, with quotation marks. Values may be strings, numbers, boolean (true, false), null, objects, or arrays. An array is an ordered list, enclosed in [brackets]:
{"pets":
[{"name": "Micky", "breed": "mouse", "weight": 0.2,
"isMale": true, "price": 1025.00,
"description": "Famous, talking mouse, married to Minnie."
},
{"name": "Minnie", "breed": "mouse", "weight": 0.3,
"isMale": false, "price": null,
"description": "Micky's adorable companion."
}
]
}
Minnie is not for sale, I guess.
JSON provides self-describing data, like XML. Values can be nested, as subtrees in XML.
JSON is often more compact than XML, because although names serve like the tags that begin an element, there is no need for closing tags; also, a single name can identify all the items in its array value. For example, here are Micky and Minnie in an XML notation:
<pet breed="mouse" name="Micky" weight="0.2" isMale="true" price="1025.00">
<description>
Famous, talking mouse, married to Minnie.
</description>
</pet>
<pet breed="mouse" name="Minnie" weight="0.3" isMale="false"
price="null">
<description>
Micky's adorable companion.
</description>
</pet>
(We would need even more XML closing tags if we had a more deeply nested structure.)
Consequently, the Python standard library describes JSON as a "lightweight data interchange format."
Import the json module from the standard library.
Use json.loads to convert a JSON string to a Python data structure; json.dumps to convert Python data structure to JSON string.
JSON strings are Unicode. Python data structures are typically dictionaries or lists, but may be simpler data types such as strings or numbers.
Example: