17.3. Processing JSON results¶
Again, python provides a module for doing this. The module is called json. We will be using two functions in this module,
json.loads() takes a string as input and produces a python object (a dictionary or a list) as output.
Consider, for example, some data that we might get from Apple’s iTunes, in the JSON format:
The other function we will use is
dumps. It does the inverse of
loads. It takes a python object, typically a dictionary or a list, and returns a string, in JSON format. It has a few other parameters. Two useful parameters are sort_keys and indent. When the value True is passed for the sort_keys parameter, the keys of dictionaries are output in alphabetic order with their values. The indent parameter expects an integer. When it is provided, dumps generates a string suitable for displaying to people, with newlines and indentation for nested lists or dictionaries. For example, the following function uses json.dumps to make a human-readable printout of a nested data structure.
Check Your Understanding