0

I am using python to get info from an API. I want to be able to prompt for a users name (firstName) and have the response get the data from the related href value.

I prompt for users name and enter "Emma". I want to access the href value based on that input. The json data looks like:

{
        "results": [
            {
                "authorised": true,
                "firstName": "Emma",
                "href": "https://192.168.1.198:8904/api/cardholders/569",
                "id": "569",
                "lastName": "Bennett"
            }
VLAZ
  • 26,331
  • 9
  • 49
  • 67
cmrussell
  • 1,912
  • 2
  • 8
  • 14

3 Answers3

0

That JSON file looks incorrect, but I suppose that's because you didn't copy and paste the entire thing. In Python, the most elegant way to handle JSON is to import the json library, whcih will give you access to encoder/decoder functions. For your purposes, you could use json.load() (for files) or json.loads() (for strings) and json.JSONDecoder() to get a Pyhon dictionary that you can access via keys.

Schnitte
  • 1,193
  • 4
  • 16
0

Firstly, it looks like you are missing two closing bracket ] and }. So if this object is stored in a variable called someJsonVar. Then you would access href by trying the following.

someJsonVar.results[0].href;

The reason you have to do results[0] is because results is an array of object elements so you have to access the first element which is the object that contains all your authorizes, firstName, href, id, and lastName fields.

0

As explained in a previous answer, you can use the json library to convert your JSON data into a Python dictionary.

Once you have your dictionary, you can do something like the following:

for result in json_dict['results']:
    if result['firstName'] == 'Emma':
        href = result['href']