Reputation: 446
I'm very new to python and still learning. I am making an API call to an application which returns some wonky output and I think I have managed to convert it to JSON. But when I try to access the JSON data using the Keys I get some error.
Below is what I have managed to do by myself -
import requests
from requests.auth import HTTPBasicAuth
import json
import re
url = 'url'
def get_FOA():
call_to_get = requests.get(url + "data", verify=False, auth=HTTPBasicAuth(username, Password))
dd = str(call_to_get.json())
dd = dd.replace("'",'"')
filed = json.dumps(dd)
filed['name']
When I run the above code, I get the below error.
Traceback (most recent call last): File "D:/joffscp/another.py", line 26, in get_FOA() File "D:/joffscp/another.py", line 19, in get_FOA filed['name'] TypeError: string indices must be integers
When I print the 'filed' which has the JSON output, I get the below.
"[{\"_ref\": \"dhcpfailover/ZG5zLmRoY3BfZmFpbG92ZXJfYXNzb2NpYXRpb24kZnJlLg:fre\", \"name\": \"fre\"}, {\"_ref\": \"dhcpfailover/ZG5zLmRoY3BfZmFpbG92ZXJfYXNzb2NpYXRpb24kdGVzdC1taWNyb3NvZnQuNg:test-microsoft/10.192.32.161\", \"name\": \"test-microsoft\"}, {\"_ref\": \"dhcpfailover/ZG5zLmRoY3BfZmFpbG92ZXJfYXNzb2NpYXRpb24kTXNfdGVzdC42:Ms_test/10.192.32.161\", \"name\": \"Ms_test\"}, {\"_ref\": \"dhcpfailover/ZG5zLmRoY3BfZmFpbG92ZXJfYXNzb2NpYXRpb24kbGV3aW5kb3dzLTEwLjE5Mi4zMi4xNjEuNg:lewindows-10.192.32.161/10.192.32.161\", \"name\": \"lewindows-10.192.32.161\"}]"
Upvotes: 0
Views: 52
Reputation: 6767
filed = json.dumps(dd)
will take an object (dd
) and turn it into a string. That's why you get the error - filed
is a string, and you can't do filed['name']
.
You already have the result of the JSON as a dictionary from call_to_get.json()
. Don't turn that into a string - and you can just do call_to_get.json()['name']
:
def get_FOA():
call_to_get = requests.get(url + "data", verify=False, auth=HTTPBasicAuth(username, Password))
filed = call_to_get.json()
return filed['name']
Upvotes: 2