Skip to content

Instantly share code, notes, and snippets.

@csonto
Created September 29, 2015 16:19
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save csonto/8baa94a22b8625a83931 to your computer and use it in GitHub Desktop.
Save csonto/8baa94a22b8625a83931 to your computer and use it in GitHub Desktop.
lvm2json - filter to format lvs as JSON
#!/usr/bin/python
"""
Filter accepting input in the form
FIELD='VALUE' FIELD2='VALUE2' ...
...
NOTE: Apostrophes are hardcoded separators and `FIELD` may contain only
uppercase letters, digits and underscores.
NOTE: this does not handle backslash escape sequences properly.
Returning JSON representation as list of dictionaries with list items
correspond to lines, dictionary to `(FIELD, VALUE)` pairs:
[
{
"FIELD": "VALUE",
"FIELD2": "VALUE2",
...
},
...
]
This is useful with `lvs`, `pvs`, `vgs` and `dmsetup info -c` commands as following:
lvs --noheadings --nameprefixes -avo+devices | lvm2json
dmsetup info -c --noheadings --nameprefixes | lvm2json
Tested with ancient LVM2-2.02.88 on RHEL5.
The heart is near single line `lvm_parse` function.
"""
import sys
import json
import re
import subprocess
_KEY_VALUE_RE=re.compile("([A-Z0-9_]*)='(([^\\\\']|\\\\.)*)'")
def lvm_parse(s):
"""
Parse output of lvs, pvs or vgs with `--nameprefixes --noheadings` and return list of dictionaries.
"""
lines=s.splitlines()
return [dict((match[0], match[1]) for match in _KEY_VALUE_RE.findall(line)) for line in lines]
if __name__ == "__main__":
if len(sys.argv) > 1:
a1 = sys.argv[1]
if a1 == "-h" or a1 == "--help":
print __doc__
else:
print >> sys.stderr, "Unknown options: %r" % sys.argv
sys.exit(1)
else:
print json.dumps(lvm_parse(sys.stdin.read()), indent=2)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment