I am trying to retrieve a value of a JSON file, but I keep getting the error
/home/pi/Desktop/asd.py:5: SyntaxWarning: list indices must be integers or slices, not str; perhaps you missed a comma?
print(str(y[['tunnels']['public_url']]))
Traceback (most recent call last):
File "/home/pi/Desktop/asd.py", line 5, in <module>
print(str(y[['tunnels']['public_url']]))
TypeError: list indices must be integers or slices, not str
Here is my code:
import json
import requests
y = requests.get('http://localhost:4040/api/tunnels').content
x = json.loads(y)
print(str(y[['tunnels']['public_url']]))
And here is the JSON file from http://localhost:4040/api/tunnels
:
{
"tunnels": [
{
"name": "command_line",
"uri": "/api/tunnels/command_line",
"public_url": "tcp://6.tcp.ngrok.io:18592",
"proto": "tcp",
"config": {
"addr": "localhost:25565",
"inspect": false
},
"metrics": {
"conns": {
"count": 166,
"gauge": 0,
"rate1": 0.017125393007699625,
"rate5": 0.027720847107677204,
"rate15": 0.02187693220653439,
"p50": 1971501053.5,
"p90": 11939627275.9,
"p95": 11991631962.25,
"p99": 19816396509.55
},
"http": {
"count": 0,
"rate1": 0,
"rate5": 0,
"rate15": 0,
"p50": 0,
"p90": 0,
"p95": 0,
"p99": 0
}
}
}
],
"uri": "/api/tunnels"
}
No matter how hard I try, I just can't seem to find a way to make this code work...
CodePudding user response:
import requests
r = requests.get('http://localhost:4040/api/tunnels')
r.json()
CodePudding user response:
print(str(y[['tunnels']['public_url']]))
There is a pair of unnecessary brackets around ['tunnels']['public_url']
which causes it to be evaluated as a slice of y. That's what caused the exception.
Try the following:
import requests
resp = requests.get('http://localhost:4040/api/tunnels')
resp_json = resp.json()
print(resp_json['tunnels']['public_url'])