Similar to the command cheat sheets I publish, this post will serve as a quick reference for short and simple Python code snippets I have used in prior projects.
Pretty Print JSON Output with Python
Un-formatted JSON can be very difficult to read. For example, take the following JSON:
{"key-one": "value-one", "key-two": "value-two"}
This example is simple to read because it is simple JSON, but it can quickly become un-readable with more keys, values, lists, and nesting of all those things.
To quickly transform the JSON output into a more human-readable format, pipe the JSON through the python -m json.tool
command to transform what you see above into the following “pretty” JSON output:
{
"key-one": "value-one",
"key-two": "value-two"
}
Print the Value of a Specific JSON Key with Python
If you want to quickly print the value of a JSON key, you can do so using the Python command with the Python code to parse the JSON passed as a string.
For example, take the following JSON:
{
"key-one": "value-one",
"key-two": "value-two"
}
To print the value of key-one, pipe the JSON to the following Python command:
python -c 'import json,sys;obj=json.load(sys.stdin); print obj["key-one"]'
Sort IP Addresses from a File
Save and point the following Python script at a file - python script.py input.txt
- which contains a list of IP addresses with one IP address per line.
#!/usr/bin/env python
from netaddr import *
import sys
input = str(sys.argv[1])
with open(input, 'r') as file:
ips = []
for ip in file:
ips += [IPAddress(ip)]
ips = sorted(ips)
for ip in ips:
print ip
Lambda Sort Strings from a File
The Python code below was used in a unique situation where I needed to sort a text file containing hostnames with the following format:
501325-object01.example.com
501319-infra02.example.com
501324-cinder01.example.com
501320-infra03.example.com
501321-logging01.example.com
501327-object03.example.com
501323-compute02.example.com
501322-compute01.example.com
501326-object02.example.com
501300-infra01.example.com
Save and point the following Python script at a file - python script.py input.txt
- that contains a list of hostnames with one hostname per line.
import sys
input = str(sys.argv[1])
with open(input, 'r') as file:
foo = file.readlines()
foo.sort(key = lambda x: x.split(".")[0].split("-",1)[1:])
for line in foo:
print line.strip()