'How would I be able to get a value from JSON?
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...
Solution 1:[1]
The requests Python module takes care of both retrieving JSON data and decoding it.
import requests
r = requests.get('http://localhost:4040/api/tunnels')
r.json()
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | wekular |
