Using JQ in python like using it through cli

Viewed 2656

I have some cli commands that run through an api and then pass to jq like so

cat json.txt | jq '.members[] | [.name] 

But now i am trying to do some logic in python and then pipe it out to jq, but i can't figure out how to do it even in a similar way to the above.

I read through the documentation for jq module in python, but i just can't get it to work, can someone please help me out with this?

3 Answers

After: pip3 install pyjq

the following runs without problems:

import pyjq
print(pyjq.all( ".members[] | [.name]", {"members": [ {"name": "foo"} ]} ))

Output:

[['foo']]

Documentation

The documentation for pyjq is at https://pypi.org/project/pyjq/

Note in particular the url optional argument.

import os

sd = os.system('cat json.txt | jq ".members[] | [.name]"')

print(sd)

Using subprocess module:

import subprocess

cmd=["cat", "json.txt", "|", "jq", "'.members[]", "|", "[.name]"]
result = subprocess.check_output(cmd, shell=True)

print(result)
Related