1. JMESPath
We work with JSON data a lot in the real world. JMESPath (“james path”) makes it easy to extract and query values from a JSON document. To use it, install the jmespath package.
1import jmespath
2
3planets = {
4 'planets': [
5 {'name': 'mercury', 'is_solid': True},
6 {'name': 'venus', 'is_solid': True},
7 {'name': 'earth', 'is_solid': True},
8 {'name': 'mars', 'is_solid': True},
9 {'name': 'jupiter', 'is_solid': False},
10 {'name': 'saturn', 'is_solid': False},
11 {'name': 'uranus', 'is_solid': False},
12 {'name': 'neptune', 'is_solid': False},
13 ]
14}
15
16print(jmespath.search('planets[*].name', planets))
17print(jmespath.search('planets[*].is_solid', planets))
For more information on JMESPath, check out the following links.
2. python-dateutil
Date and time information is everywhere. It is not easy to parse, clean and format date and time information. The python-dateutil package can help ease the pain of dealing with date and time data.
1from dateutil.parser import parse
2
3logline = 'INFO 2021-12-31T23:59:11 Almost new year!'
4timestamp = parse(logline, fuzzy=True)
5print(timestamp)
3. termtables
If you have tabular data, you will find yourself wanting to pretty print the content from time to time if the data is not so big. There are many libraries to help you do so.
1import termtables as tt
2
3header = ['first_name', 'last_name', 'age', 'height', 'is_cool']
4data = [
5 ['john', 'doe', 23, 5.5, True],
6 ['jack', 'johnson', 34, 6.2, False]
7]
8
9tt.print(
10 data,
11 header=header,
12 style=tt.styles.markdown,
13 padding=(0, 1),
14 alignment="lcrlc"
15)
4. Exercise
Build a tiny command-line report that combines third-party tools:
use
python-dateutilto parse three date strings in different formatsstore the parsed data in dictionaries
use
JMESPathto extract only the fields you want to displayprint the final result as a table with
termtablesortabulate