Search code examples
pythonrequestresponse

Python - print some data from response


I'm making a request:

import request in python:
url = "http://myweb.com/call" 
payload  = {} 
headers = {   'Content-Type': 'application/json',   'Token': '123456789' }

response = requests.request("POST", url, headers=headers, data = payload)
print(response.text.encode('utf8'))

and I'm receiving and printing the response as :

{"name":"Peter","LastName":JOHN,"RegDate":"2020-03-25T17:34:42.5306823Z","Number":7755}

but I want the print statement to show only "Name" and "Number" params. Not the whole response should be printed. How do I do this? Thanks in advance.


Solution

  • You can do this:

    import json
    
    response = requests.request("POST", url, headers=headers, data = payload)
    response_txt=json.loads(response.text.encode('utf8'))
    print(response_txt['name'])
    print(response_txt['Number'])
    

    response.text.encode('utf8') produces a string, so you need import the json library and convert that string to an object with json.loads. Then you can access the keys with response_txt['name'] and response_txt['Number'].