Skip to content

Instantly share code, notes, and snippets.

@alswl
Created August 26, 2016 07:13
Show Gist options
  • Save alswl/eee052f75437445e67f91feac335dc0e to your computer and use it in GitHub Desktop.
Save alswl/eee052f75437445e67f91feac335dc0e to your computer and use it in GitHub Desktop.
simple jq call via subprocess
# coding=utf-8
import subprocess
import json
import os
import time
JQ_BIN_LINUX = '/usr/bin/jq'
JQ_BIN_MAC = '/usr/local/bin/jq'
if os.path.isfile(JQ_BIN_LINUX):
JQ_BIN = JQ_BIN_LINUX
elif os.path.isfile(JQ_BIN_MAC):
JQ_BIN = JQ_BIN_MAC
else:
raise ValueError('NO jq')
def jq(input, parameter, is_multiple_output=False):
input_json = json.dumps(input)
tmp_file_path = '/tmp/jq_%s' % time.time()
with open(tmp_file_path, 'w') as f:
f.write(input_json.encode('utf-8'))
p_jq = subprocess.Popen([JQ_BIN, parameter, tmp_file_path], stdout=subprocess.PIPE)
output = p_jq.communicate()[0]
if is_multiple_output:
output_json = json.loads('[' + output.replace('\n', ',')[:-1] + ']')
else:
output_json = json.loads(output)
return output_json
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment