I'm trying to execute a jq command from my python script. Currently the jq command is working fine when I execute from the terminal (MacOs).
cat filename.json |jq '{Name:.name, address:.address[0][1].street}'
Basically I'm trying to extract data from a JSON using jq. As the JSON contains nested arrays, I would have to loop using a variable.
My questions is -
I don't want to use any language other than python, as it would cause compatibility issues.
1- you can start jq like any other external program ( subprocess module) 2- to extract data from JSON, use json module in Python (no need to run any shell command). Provide example JSON input and the desired output and what you get instead.
You can seamlessly call jq script (like regular expression) and process a plain python data structure.
Example-1: Search key in simple JSON data Here, a variable named customerData is defined to store the JSON data. The value of the key will be taken as input from the user. loads() method of JSON module is used to load JSON data in the variable named customer. Next, 'in' operator is used to search the key.
jq command is used not only for reading JSON data but also to display data by removing the particular key. The following command will print all key values of Students. json file by excluding batch key. map and del function are used in jq command to do the task.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With