Get fields from a specific Jira issue - python

I'm trying to get all the fields and values from a specific issue my code:
authenticated_jira = JIRA(options={'server': self.jira_server}, basic_auth=(self.jira_username, self.jira_password))
issue = authenticated_jira.issue(self.id)
print issue.fields()
Instead of returning the list of fields it returns:
<jira.resources.PropertyHolder object at 0x108431390>

authenticated_jira = JIRA(options={'server': self.jira_server}, basic_auth=(self.jira_username, self.jira_password))
issue = authenticated_jira.issue(self.id)
for field_name in issue.raw['fields']:
print "Field:", field_name, "Value:", issue.raw['fields'][field_name]
Depends on field type, sometimes you get dictionary as a value and then you have to find the actual value you want.

Found using:
print self.issue_object.raw
which returns the raw json dictionary which can be iterate and manipulate.

You can use issue.raw['fields']['desired_field'], but this way is kind of indirectly accessing the field values, because what you get in return is not consistent. You get lists of strings, then just strings themselves, and then straight up values that don't have a key for you to access them with, so you'll have to iterate, count the location, and then parse to get value which is unreliable.
Best way is to use issue.fields.customfield_# This way you don't have to do any parsing through the .raw fields
Almost everything has a customfield associated with it. You can pull just issues from REST API to find customfield #'s, or some of the fields that you get from using .raw will have a customfield id that should look like "customfield_11111" and that's what you'll use.

Using Answer from #kobi-k but dumping in better format, I used following code:
with open("fields.txt", "w") as f:
json.dump(issue.raw, f, indent=4)
It dumped all the fields in a file with name "fields.txt"

Related

Update document with pyarango

I have an existing arango document that I get from a key:
doc = collection[key]
I used to update using:
for key, value in new_data.item():
doc[key] = value
doc.save()
Sometime, new_data has an empty field and I want to remove this field from the doc.
I must miss something, since nothing I tried seems to work:
doc.patch(keep_null=True, **new_data)
doc.patch(keep_null=False, **new_data)
doc.set(new_data)
I tried with set() and getStore() too (when new_data is an arango doc)
I wanted to iterate on doc keys (using getStore), but I don't know how to delete a field from a doc...
How do I replace doc data by "new data" (which is an arango doc with same _key/_id)? Any help is appreciated!
Was trying to figure out how to do this earlier today. What you need to do is
del arangodoc["key"]
arangodoc.save()#the save is important, patch won't delete the missing field.

How to parse multiple files in multipart form-data with django rest framework?

I am receiving an array with a few files. My request.data looks like this:
<QueryDict: {'image': [<TemporaryUploadedFile: image_1.png (image/png)>, <TemporaryUploadedFile: image_2.png (image/png)>]
However, if I try to parse images like this:
request.data['image']
I only can see the last image, and django rest framework recognize it as a file object, not a list.
If I try to iterate over it all I can see is bytes.
I am using a ModelViewset and added this parsers
parser_classes = (MultiPartParser, FormParser)
A QueryDict has a special function to obtain all values associated with a specific key: getlist(key) [doc]. So you can write it like:
request.data.getlist('image') # list of images
You can then process every image separately (for example in a for loop).
Or like specified in the documentation:
QueryDict.getlist(key, default=None)
Returns a list of the data with the requested key. Returns an empty list if the key doesn't exist and a default value wasn’t provided. It's guaranteed to return a list unless the default value provided is' a list.
If you perform indexing (like request.data[key]), then Python will call __getitem__ behind the curtains, and this will result in:
QueryDict.__getitem__(key)
Returns the value for the given key. If the key has more than one value, it returns the last value. Raises django.utils.datastructures.MultiValueDictKeyError if the key does not exist. (This is a subclass of Python's standard KeyError, so you can stick to catching KeyError.)

Python 2.7 replace all instances of NULL / NONE in complex JSON object

I have the following code..
.... rest api call >> response
rsp = response.json()
print json2html.convert(rsp)
which results in the following
error: Can't convert NULL!
I therefore started looking into schemes to replace all None / Null's in my JSON response, but I'm having an issue since the JSON returned from the api is complex and nested many levels and I don't know where the NULL will actually appear.
From what I can tell I need to iterate over the dictionary objects recursively and check for any values that are NONE and actually rebuild the object with the values replaced, but I don't really know where to start since dictionary objects are immutable..
If you look at json2html's source it seems like you have a different problem - and the error message is not helping.
Try to use it like this:
print json2html.convert(json=rsp)
btw. because I've already contributed to that project a bit I've opened up the following PR due to this question: https://github.com/softvar/json2html/pull/20

Parsing JSON in Python (Reverse dictionary search)

I'm using Python and "requests" to practice the use of API. I've had success with basic requests and parsing, but having difficulty with list comprehension for a more complex project.
I requested from a server and got a dictionary. From there, I used:
participant_search = (match1_request['participantIdentities'])
To convert the values of the participantIdentities key to get the following data:
[{'player':
{'summonerName': 'Crescent Bladex',
'matchHistoryUri': '/v1/stats/player_history/NA1/226413119',
'summonerId': 63523774,
'profileIcon': 870},
'participantId': 1},
My goal here is to combine the summonerId and participantId to one list. Which is easy normally, but the order of ParticipantIdentities is randomized. So the player I want information on will sometimes be 1st on the list, and other times third.
So I can't use the var = list[0] like how I would normally do.
I have access to summonerId, so I'm thinking I can search the list the summonerId, then somehow collect all the information around it. For instance, if I knew 63523774 then I could find the key for it. From here, is it possible to find the parent list of the key?
Any guidance would be appreciated.
Edit (Clarification):
Here's the data I'm working with: http://pastebin.com/spHk8VP0
At line 1691 is where participant the nested dictionary 'participantIdentities' is. From here, there are 10 dictionaries. These 10 dictionaries include two nested dictionaries, "player" and "participantId".
My goal is to search these 10 dictionaries for the one dictionary that has the summonerId. The summonerId is something I already know before I make this request to the server.
So I'm looking for some sort of "search" method, that goes beyond "true/false". A search method that, if a value is found within an object, the entire dictionary (key:value) is given.
Not sure if I properly understood you, but would this work?
for i in range(len(match1_request['participantIdentities'])):
if(match1_request['participantIdentities'][i]['summonerid'] == '63523774':
# do whatever you want with it.
i becomes the index you're searching for.
ds = match1_request['participantIdentities']
result_ = [d for d in ds if d["player"]["summonerId"] == 12345]
result = result_[0] if result_ else {}
See if it works for you.
You can use a dict comprehension to build a dict wich uses summonerIds as keys:
players_list = response['participantIdentities']
{p['player']['summonerId']: p['participantId'] for p in players_list}
I think what you are asking for is: "How do I get the stats for a given a summoner?"
You'll need a mapping of participantId to summonerId.
For example, would it be helpful to know this?
summoner[1] = 63523774
summoner[2] = 44610089
...
If so, then:
# This is probably what you are asking for:
summoner = {ident['participantId']: ident['player']['summonerId']
for ident in match1_request['participantIdentities']}
# Then you can do this:
summoner_stats = {summoner[p['participantId']]: p['stats']
for p in match1_request['participants']}
# And to lookup a particular summoner's stats:
print summoner_stats[44610089]
(ref: raw data you pasted)

Parsing JSON string/object in Python

I've recently started working with JSON in python. Now I'm passing a JSON string to Python(Django) through a post request. Now I want to parse/iterate of that data. But I can't find a elegant way to parse this data, which somehow I'm pretty sure exists.
data = request.POST['postformdata']
print data
{"c1r1":"{\"Choice\":\"i1\"}","c2r1":"{\"Bool\":\"i2\"}","c1r2":"{\"Chars\":\"i3\"}"}
jdata = json.loads(data)
print jdata
{u'c1r2': u'{"Chars":"i3"}', u'c1r1': u'{"Choice":"i1"}', u'c2r1': u'{"Bool":"i2"}'}
This is what was expected. But now when I want to get the values, I start running into problems. I have to do something like
mydecoder = json.JSONDecoder()
for part in mydecoder.decode(data):
print part
# c1r2 c1r1 c2r1 ,//Was expecting values as well
I was hoping to get the value + key, instead of just the key. Now, I have to use the keys to get values using something like
print jdata[key]
How do I iterate over this data in a simpler fashion, so that I can iterate over key, values?
To iterate key and value, you can write
for key, value in jdata.iteritems():
print key, value
You can read the document here: dict.iteritems
Just for others to help. In Python3 dict.iteritems() has been renamed to dict.iter()

Categories