Python Forum
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
curl and jq on python
#1
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
Reply
#2
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
Almost dead, but too lazy to die: https://sourceserver.info
All humans together. We don't need politicians!
Reply
#3
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
Reply
#4
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.).
Reply


Possibly Related Threads…
Thread Author Replies Views Last Post
  How do loop over curl and 'put' different values in API call? onenessboy 0 1,219 Jun-05-2022, 05:24 AM
Last Post: onenessboy
  how can I correct the Bad Request error on my curl request tomtom 8 5,060 Oct-03-2021, 06:32 AM
Last Post: tomtom
  Works with Curl. Can't get it to work in Python bazcurtis 3 2,538 May-07-2020, 07:47 AM
Last Post: bazcurtis
  Curl command to python requests pythonclass 0 3,411 Apr-12-2019, 06:29 PM
Last Post: pythonclass

Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020