Python has two data types that, together, form the perfect tool for working with JSON: dictionaries and lists. Let’s explore how to:

  • load and write JSON
  • Pretty-print and validate JSON on the command line
  • Do advanced queries on JSON docs by using JMESPath

1. Decoding JSON

Python ships with a powerful and elegant  JSON library. It can be imported with:

import json

Decoding a string of JSON is as simple as json.loads(…) (short for load string).

It converts:

  • objects to dictionaries
  • arrays to lists,
  • booleans, integers, floats, and strings are recognized for what they are and will be converted into the correct types in Python
  • Any null will be converted into Python’s None type

Here’s an example of json.loads in action:

>>> import json
>>> jsonstring = '{"name": "erik", "age": 38, "married": true}'
>>> json.loads(jsonstring)
{'name': 'erik', 'age': 38, 'married': True}

#python #data-science

4 Tricks to Effectively Use JSON in Python
15.90 GEEK