Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
496 views
in Technique[技术] by (71.8m points)

python - Retrieving items from a dictionary data type created from a JSON request

I've tried every way I can find to loop through the member items in the JSON returned below by this code:

import requests,string,simplejson as json
from pprint import pprint

data=requests.get('http://localhost:8090/api/v1/members/2321')
data  = json.loads(data.text)

pprint(data)

The results of this pprint are:

{u'members': [[{u'member_amt_pledged': u'10.00',
u'member_amt_recvd': None,
u'member_id': u'1',
u'name': u'Murray Hight'},
{u'member_amt_pledged': u'10.00',
u'member_amt_recvd': None,
u'member_id': u'4',
u'name': u'Martin Tunis'}]],
u'error': False}

How can I loop through this data member data and evaluate and print each line?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

The data in your code is a python dictionary. A key value pair.

You can access items in a dictionary with a variable[key] format. In your case as:

data['members']

this prints

[[{u'member_amt_pledged': u'10.00',
   u'member_amt_recvd': None,
   u'member_id': u'1',
   u'name': u'Murray Hight'},
  {u'member_amt_pledged': u'10.00',
   u'member_amt_recvd': None,
   u'member_id': u'4',
   u'name': u'Martin Tunis'}]]

so data['members'] is a list of a list. Access it's first item as data['members'][0]. This is still a list. So you iterate over it as:

for item in data['members'][0]:
    print(item)

this gives you:

{u'member_amt_recvd': None, u'member_amt_pledged': u'10.00', u'name': u'Murray Hight', u'member_id': u'1'}
{u'member_amt_recvd': None, u'member_amt_pledged': u'10.00', u'name': u'Martin Tunis', u'member_id': u'4'}

As you can see, each of these are dictionaries, so you access it's items as:

for item in data['members'][0]:
    print(item['member_amt_pledged'])
    print(item['member_amt_recvd'])
    print(item['member_id'])
    print(item['name'])

this gives you:

10.00
None
1
Murray Hight
10.00
None
4
Martin Tunis

Hope this helps.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...