New to python here. I'm trying to iterate over all the JSON "group" objects for each person but having some difficulty. This is only a partial list (not all users have groups) so I need to use the try/catch block so users without a list of groups don't cause early termination.
The JSON data snippet:
{
"people": [
{
"person": {
"name": "joe",
"email": "joe#foo.net",
"groups": [
{
"name": "office",
"id": 23
},
{
"name": "mfg",
"id": 93
} ]
},
"person": {
"name": "bill",
"email": "bill#foo.net",
"groups": [
{
"name": "acctg",
"id": 133
},
{
"name": "mgr",
"id": 207
} ]
}
}
]
}
This is my code so far:
jdata = json.loads...
for person in jdata['people']:
for key, val in person.iteritems():
print "key ", key , " is ", val
print val["name"]
print val["email"]
try:
for gkey, gval in val["groups"][0].iteritems():
print "gval: " + gval
except:
foo=1
Notice I can print out a list of the 0th item in the group list by doing the for gkey...val["groups"][0].iteritems() but what I really want is iterate over all the group lists of each person entry (some people belong to two groups, others 10 or more) so there is no fixed length. How can I do this?
Is that what you want? :
>>> for group in j['people'][0]['person']['groups']:
for k,v in group.items():
print(k,v)
name acctg
id 133
name mgr
id 207
Or more generally:
>>> for person in j['people']:
for group in person['person']['groups']:
print('Name : {} --- ID: {}'.format(group['name'], group['id']))
Name : acctg --- ID: 133
Name : mgr --- ID: 207
Related
I have a field where value is as below
b = [
{
"category": "Engineer",
"name": "Anthony Test",
"id": 219
},
{
"category": "Engineer",
"name": "Pete Junior",
"id": 220
}
]
I would like to get the result in below format where I want to eliminate category and create a dictionary with id and name
result = {'219': 'Anthony Test', '220': 'Pete Junior'}
You can use dictionary comprehension
{i['id']: i['name'] for i in b}
What are the options for extracting value from JSON depending on other parameters (using python)? For example, JSON:
"list": [
{
"name": "value",
"id": "123456789"
},
{
"name": "needed-value",
"id": "987654321"
}
]
When using json_name["list"][0]["id"] it obviously returns 123456789. Is there a way to indicate "name" value "needed-value" so i could get 987654321 in return?
For example:
import json as j
s = '''
{
"list": [
{
"name": "value",
"id": "123456789"
},
{
"name": "needed-value",
"id": "987654321"
}
]
}
'''
js = j.loads(s)
print [x["id"] for x in js["list"] if x["name"] == "needed-value"]
The best way to handle this is to refactor the json as a single dictionary. Since "name" and "id" are redundant you can make the dictionary with the value from "name" as the key and the value from "id" as the value.
import json
j = '''{
"list":[
{
"name": "value",
"id": "123456789"
},{
"name": "needed-value",
"id": "987654321"
}
]
}'''
jlist = json.loads(j)['list']
d = {jd['name']: jd['id'] for jd in jlist}
print(d) ##{'value': '123456789', 'needed-value': '987654321'}
Now you can iterate the items like you normally would from a dictionary.
for k, v in d.items():
print(k, v)
# value 123456789
# needed-value 987654321
And since the names are now hashed, you can check membership more efficiently than continually querying the list.
assert 'needed-value' in d
jsn = {
"list": [
{
"name": "value",
"id": "123456789"
},
{
"name": "needed-value",
"id": "987654321"
}
]
}
def get_id(list, name):
for el in list:
if el['name'] == name:
yield el['id']
print(list(get_id(jsn['list'], 'needed-value')))
Python innately treats JSON as a list of dictionaries. With this in mind, you can call the index of the list you need to be returned since you know it's location in the list (and child dictionary).
In your case, I would use list[1]["id"]
If, however, you don't know where the position of your needed value is within the list, the you can run an old fashioned for loop this way:
for user in list:
if user["name"] == "needed_value":
return user["id"]
This is assuming you only have one unique needed_value in your list.
I am trying to parse output from Get API. My response text is:
{
"data": [
{
"date_created": "22:20:47",
"name": "test1",
"id": "12345",
"status": "0"
},
{
"date_created": "00:09:17",
"name": "test2",
"id": "23456",
"status": "0"
},
{
"date_created": "00:08:02",
"name": "test3",
"id": "34567",
"status": "0"
},
I have ~100 ids. I need to print only ids and search for specific id from list.
so far, i parse with next method:
json_data = get_req.text
python_data = json.loads(json_data)
id = python_data["data"][0]["id"]
print "Object id: ", id
But it is printing only one ID, where i need all of them.
Do you have any ideas how can i print all of them?
Try using this below code snippet:
for i in range(len(python_data["data"])):
print(python_data["data"][i]["id"])
I got the expected output :
12345
23456
34567
you have a list of dicts so you need loop:
ids = [x.get('id') for x in python_data["data"]]
print (ids)
I looked through some other answers but I don't fully understand. There are no duplicate values.
{
"type": "champion",
"data": {
"89": {
"title": "the Radiant Dawn",
"name": "Leona"
},
"110":{
"title": "the Arrow of Retribution",
"name": "Varus"
}
}
}
what I have, I'm not sure how to proceed. In the actual dict there's more information than just title and key
championID = 0
for key, value in championData["data"].items():
for childkey,childvalue in value.items():
#
champion = getChamp(championID)
I want to input a name and have it return the ID (the number, 89 and 110 are listed). For example, inputting Leona would return 89.
(Sorry, I could have done a better job of asking the question at the beginning :'v)
This will work:
championData = {"type": "champion", "data": {
"89": {
"title": "the Radiant Dawn",
"name": "Leona"
},
"110": {
"title": "the Arrow of Retribution",
"name": "Varus"
}
}}
name = "Leona"
data = championData['data']
for championId in data:
if(data[championId]['name']) == name:
print(championId)
The output is: 89
I have a list of dictionaries with 2 keys: 'name' & 'value'. I need to get the value of 'value' key if value of 'name' key is 'Subject'
Currently i'm iterating through each dict and checking the value of 'name' and getting the value of 'value'. Is there any improved way of doing this ?
items = [
{
"name": "From",
"value": "from#example.com"
},
{
"name": "Date",
"value": "Tue, 8 Sep 2014 16:18:35 +0530"
},
{
"name": "Subject",
"value": "Test Subject"
},
{
"name": "To",
"value": "sender#example.com"
},
]
for item in items:
if item.get('name') == 'Subject':
print "Subject: " + item.get('value')
You should transpose your data into a dict instead:
>>> d = dict([(e['name'],e['value']) for e in items]) # transpose
Or a slightly easier way as mentioned by Peter Wood in the comments:
>>> d = {e['name']: e['value'] for e in items}
Then just use the dict as normal:
>>> d['Subject']
'Test Subject'
You could use next along with a generator filtering and converting the items.
>>> subject = next(field['value']
... for field in items
... if field['name'] == 'Subject')
As Jonas told, better for modify your structure because
from collections import defaultdict
it = [
{
"name": "From",
"value": "from#example.com"
},
{
"name": "Date",
"value": "Tue, 8 Sep 2014 16:18:35 +0530"
},
{
"name": "Subject",
"value": "Test Subject"
},
{
"name": "Subject",
"value": "Test Subject 55"
},
{
"name": "To",
"value": "sender#example.com"
},
]
result = defaultdict(list)
# shorcut better to use for...
[result[item["name"]].append(item["value"]) for item in it]
print(result["Subject"])
['Test Subject', 'Test Subject 55']