Knowledge Base

Preserving for the future: Shell scripts, AoC, and more

Python3 run command and convert stdout from csv to json

Because apparently this is a non-trivial process to find on the Internet.

import os, sys, subprocess, json, csv

def get_json(username):
   result = []
   # https://stackoverflow.com/a/19706994
   # https://stackoverflow.com/a/33927495
   # https://stackoverflow.com/a/8880539
   cmd = "/path/to/csv-generator.sh"
   a = subprocess.Popen([cmd,username], stdout=subprocess.PIPE) # output is a CSV
   b = a.communicate()[0].decode('utf-8')
   c = csv.DictReader(b.splitlines())
   # fieldnames must be left undefined, to read first row as column titles
   for row in c:
      try:
         row.pop("") # try removing blank key, because CSV is proper format and ends with trailing comma
      except:
         pass
      result.append(row)
   return json.dumps(result)

if __name__ == "__main__":
   print(get_json("bgstack15"))

And in the future, use AD groups for access control instead of a custom database, devs...

Comments