Home > Blockchain >  Reading key values a JSON array which is a set in Python
Reading key values a JSON array which is a set in Python

Time:01-20

I have the following code

import requests
import json
import sys

credentials_User=sys.argv[1]
credentials_Password=sys.argv[2]
email=sys.argv[3]

def auth_api(login_User,login_Password,):

    gooddata_user=login_User
    gooddata_password=login_Password
    body = json.dumps({
    "postUserLogin":{
        "login": gooddata_user,
        "password": gooddata_password,
        "remember":1,
        "verify_level":0
    }
    })
    headers = {
    'Content-Type': 'application/json',
    'Accept': 'application/json'
    }

    url="https://reports.domain.com/gdc/account/login"

    response = requests.request(
        "POST",
        url,
        headers=headers,
        data=body
    )
    sst=response.headers.get('Set-Cookie')
    return sst

def query_api(cookie,email):

    url="https://reports.domain.com/gdc/account/domains/domain/users?login=" email
    
    body={}

    headers={
        'Content-Type': 'application/json',
        'Accept': 'application/json',
        'Cookie': cookie
    }

    response = requests.request(
        "GET",
        url,
        headers=headers,
        data=body
    )
    jsonContent=[]
    jsonContent.append({response.text})
    accountSettings=jsonContent[0]
    print(accountSettings)


cookie=auth_api(credentials_User,credentials_Password)
profilehash=query_api(cookie,email)

The code itself works and sends a request to the Gooddata API.

The query_api() function returns JSON similar to below

{
  "accountSettings": {
    "items": [
      {
        "accountSetting": {
          "login": "[email protected]",
          "email": "[email protected]",
          "firstName": "First Name",
          "lastName": "Last Name",
          "companyName": "Company Name",
          "position": "Data Analyst",
          "created": "2020-01-08 15:44:23",
          "updated": "2020-01-08 15:44:23",
          "timezone": null,
          "country": "United States",
          "phoneNumber": "(425) 555-1111",
          "old_password": "secret$123",
          "password": "secret$234",
          "verifyPassword": "secret$234",
          "authenticationModes": [
            "SSO"
          ],
          "ssoProvider": "sso-domain.com",
          "language": "en-US",
          "ipWhitelist": [
            "127.0.0.1"
          ],
          "links": {
            "projects": "/gdc/account/profile/{profile_id}/projects",
            "self": "/gdc/account/profile/{profile_id}",
            "domain": "/gdc/domains/default",
            "auditEvents": "/gdc/account/profile/{profile_id}/auditEvents"
          },
          "effectiveIpWhitelist": "[ 127.0.0.1 ]"
        }
      }
    ],
    "paging": {
      "offset": 20,
      "count": 100,
      "next": "/gdc/uri?offset=100"
    }
  }
}

The issue I am having is reading specific keys from this JSON Dict, I can use accountSettings=jsonContent[0] but that just returns the same JSON.

What I want to do is read the value of the project key within links

How would I do this with a dict?

Thanks

CodePudding user response:

Based on your description, uyou have your value inside a list, (not a set. Foergt about set: sets are not used with JSON). Inside your list, you either your content as a single string, which then you'd have to parse with json.loads, or it is simply a well behaved nested data structure already extracted from JSON, but which is inside a single element list. This seems the most likely.

So, you should be able to do:

accountlink = jsonContent[0]["items"][0]["accountSetting"]["login"]

otherwise, if it is encoded as a a json string, you have to parse it first:

import json
accountlink = json.loads(jsonContent[0])["items"][0]["accountSetting"]["login"]

Now, given your question, I'd say your are on a begginer level as a programmer, or a casual user, just using Python to automatize something either way, I'd recommend you do try some exercising before proceeding: it will save you time (a lot of time). I am not trying to bully or mock anything here: this is the best advice I can offer you. Seek for tutorials that play around on the interactive mode, rather than trying entire programs at once that you'd just copy and paste.

CodePudding user response:

Using the below code fixed the issue

jsonContent=json.loads(response.text)
print(type(jsonContent))
test=jsonContent["accountSettings"]["items"][0]
test2=test["accountSetting"]["links"]["self"]
print(test)
print(test2)

I believe this works because for some reason I didn't notice I was using .append for my jsonContent. This resulted in the data type being something other than it should have been.

Thanks to everyone who tried helping me.

  •  Tags:  
  • Related