Home > database >  Print just the value of one json key response with python
Print just the value of one json key response with python

Time:11-09

I'm new on it all. I have a url that returns me a token, in a json format. This token changes all the time I call this url. It's something like this:

{
"token": {
    "token": "randomtoken",
    "result": 1,
    "resultCode": "2",
    "requestId": "3"
}}

I want to print just the result of token key when I call my python code, which is like this:

import requests as req

resp = req.get("http://myurl.com.br")

print(resp.text)

This python code is returning me the following result:

{"token":{"token":"randomtoken","result":1,"resultCode":"2","requestId":"3"}}

How can I print just the token key result? Like just:

"randomtoken" 

It's possible?

CodePudding user response:

You have a dict so you may access it with its keys as string

import requests as req

resp = req.get("http://myurl.com.br")
token_key = resp.json()['token']['token']
print(token_key)

Note that

  • resp.text returns a string, you would need json.loads(resp.text) to get a dict
  • resp.json() does the loading from the text

CodePudding user response:

import json
t = json.loads(resp.text)
print(t["token"]["token"])
  • Related