Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is there a way to execute jq from python

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 -

  • Can I execute this command from a python script
  • If it can be done, then how would I loop through for the nested array
  • elements in the sample data give above (address[][].street)

I don't want to use any language other than python, as it would cause compatibility issues.

like image 829
FirstName Avatar asked Jul 06 '16 09:07

FirstName


People also ask

How do you run a jq in Python script?

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.

Can we use jq in Python?

You can seamlessly call jq script (like regular expression) and process a plain python data structure.

How do I query JSON data in Python?

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.

How do I run a jq in bash?

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.


1 Answers

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.

like image 148
peak Avatar answered Sep 22 '22 08:09

peak