Python Forum
curl and jq on python - Printable Version

+- Python Forum (https://python-forum.io)
+-- Forum: Python Coding (https://python-forum.io/forum-7.html)
+--- Forum: General Coding Help (https://python-forum.io/forum-8.html)
+--- Thread: curl and jq on python (/thread-24702.html)



curl and jq on python - enigma619 - Feb-28-2020

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


RE: curl and jq on python - DeaD_EyE - Feb-28-2020

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/master/user/quickstart/#json-response-content


RE: curl and jq on python - enigma619 - Feb-28-2020

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


RE: curl and jq on python - ndc85430 - Feb-29-2020

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.).