Python Forum

Full Version: curl and jq on python
You're currently viewing a stripped down version of our content. View the full version with proper formatting.
Hi

I've a question about a request I need to do on a python script.
In fact I use icinga and my request on bash is:
curl -k -s -u admin:XXXXXXXX H 'Accept: application/json'   'https://localhost:5665/v1/objects/hosts' | jq '.' | grep -c '__name'
I can do curl request but not succeed to use jq and grep after.

            request_url = "https://localhost:5665/v1/hosts"

            headers = {
                'Accept': 'application/json',
                 'X-HTTP-Method-Override': 'GET'
            }
            r = requests.post(request_url,
            headers=headers,
            verify=True,
            auth=(api_login, api_password),)
But for jq..
If you have any ideas please?
(I try with many docs examples but not with success)

Thanks

Alex
Python has a json module in the standard library.
The response object from request.get has a json method you could use.
This is also the cause why it's called Requests for Humans. They made many abstractions for us.


request_url = "https://localhost:5665/v1/hosts"

headers = {
    'Accept': 'application/json',
    'X-HTTP-Method-Override': 'GET',
}

r = requests.post(
    request_url,
    headers=headers,
    verify=True,
    auth=(api_login, api_password),
).json()  #  <<-  json Method of returned object.
json module in Python standard lib: https://docs.python.org/3/library/json.html
response from requests has the method json: https://requests.readthedocs.io/en/maste...se-content
Thanks with .json() it sounds better with first result.
(and thanks for your clear explanation)

Now i need to apply "| jq '.' | grep -c '__name'" on this r result.

But i don't succeed to retrieve result (I'm trying with many means..)

Thanks
I think you're missing the point: in a programming language, you don't tend to use external programs. If you follow the advice given above, you'll get the JSON in Python data structures (e.g. dictionaries for objects), so can process them in the usual way (e.g. by iterating over them, accessing specific items, etc.).