arrays – Is there a way to execute jq from python
arrays – Is there a way to execute jq from python
From the jq FAQ:
Q: What bindings are available for Python?
A:
pip install jq # For details, see https://pypi.python.org/pypi/jq
pip install pyjq # For details, see https://pypi.python.org/pypi/pyjq
As for your nested array, looping through it sounds like something that can (and maybe should) be done within jq.
I believe the accepted answer should be peaks one, as the proper way to use a C api in python is via a python binding lib, and both https://pypi.python.org/pypi/jq and https://pypi.python.org/pypi/pyjq should work as expected.
That being said, since we are talking about python, I would like to bring an alternative that is much more pythonic: glom (pip install glom
, https://glom.readthedocs.io/)
Instead of using a DSL like in jq
, with glom
you just declare the output in the format you want, using pure python (this output format is called spec
). In this case, you want a simple dict
:
spec = {Name: name,
street: address.0.1.street}
and then just call glom on your data:
output_data = glom(input_data, spec)
Just like jq
, you can also use glom
on command line:
cat filename.json | glom {Name: name, street: address.0.1.street}
A complete python example:
import json
from pprint import pprint
from glom import glom
with open(filename.json, rt) as f:
input_data = json.load(f)
spec = {Name: name,
street: address.0.1.street}
output_data = glom(input_data, spec)
pprint(output_data)
arrays – Is there a way to execute jq from python
Well, Im a big fan of jq, but it doesnt seem like youre doing something that cant be easily done in Python too. Consider:
import json
with open(filename.json, r) as f:
data = json.load(f)
{Name: data[name], address: data[address][0][1][street]}