Home > database >  Pulling out certain values passed in through a string
Pulling out certain values passed in through a string

Time:01-25

I need to pull out certain values of a string.

Part of python string is

{"expand":"schema,names","startAt":0,"total":1244,"issues":[{"id":"1","self":"xxxxxxxx","key":"UKTEST-33982","fields":{"Test":"Test1","priority":{"name":"Critical","id":"10000"}}},{"id":"2","self":"xxxxxxxx","key":"UKTEST-10674","fields":{"Test":"Test2","priority":{"name":"medium","id":"10001"}}}]}
I require to pull out the key field "UKTEST-33982" and "UKTEST-10674" and so forth.

Here is my code so far (ive taken out the username and password):

import requests
from requests.structures import CaseInsensitiveDict


url = "https://xxxx.com/xxxxxx/rest/api/2/search?xxxx=project=UKTEST"


r = requests.get(url, auth=(username, password))
packages_json = r.json ()
packages_str = json.dumps(packages_json)

print(packages_str)

I've had a look through the documentation and can't find what function to use.

CodePudding user response:

if you want to pull out all the ["issues"][n]["key"] you can do:

json = {"expand":"schema,names","startAt":0,"total":1244,"issues":[{"id":"1","self":"xxxxxxxx","key":"UKTEST-33982","fields":{"Test":"Test1","priority":{"name":"Critical","id":"10000"}}},{"id":"2","self":"xxxxxxxx","key":"UKTEST-10674","fields":{"Test":"Test2","priority":{"name":"medium","id":"10001"}}}]}
keys = [issue["key"] for issue in json["issues"]]
print(keys)

CodePudding user response:

Are you just trying to pull out the value from a dictionary? Thing is, json.dumps turns the object into a string, so you can't actually do anything with it. You want to do

import requests
from requests.structures import CaseInsensitiveDict


url = "https://xxxx.com/xxxxxx/rest/api/2/search?xxxx=project=UKTEST"


r = requests.get(url, auth=(username, password))
packages_json = r.json ()
print(packages_json['issues'][0]['key'])


I think

CodePudding user response:

In order to get all keys you can iterate over your JSON result. Similar to this:

r = requests.get(url, auth=(username, password))
packages_json = r.json()

keys = []
for issue in packages_json['issues']:
    keys.append(issue['key'])
    
print(keys)

Output should be:

['UKTEST-33982', 'UKTEST-10674']
  •  Tags:  
  • Related