Reputation: 3640
I have a Python object called Profile
which has first name
and last name
. I have an array called Profiles
which is a collection of Profile
objects:
Profiles = []
Profile = {}
Profile['firstname'] = "foo"
Profile['lastname'] = "bar"
Profiles.append(Profile)
I need to post this array as json to a web service, however I only want to post the firstname property.
I'm posting the array like this:
response = urllib2.urlopen(req, json.dumps(Profiles))
How can I modify my code to only post the first names? I realise I can loop through and create a new list, but was wondering if there was an easier way?
Upvotes: 1
Views: 2021
Reputation: 1060
Here you go:
json.dumps([p['firstname'] for p in Profiles])
And for two fields, you can just write:
json.dumps([{'firstname':p['firstname'],'lastname':p['lastname']} for p in Profiles])
Upvotes: 1
Reputation: 22954
Iterate over the list and extract the desired elements from the dict
using list comprehension.
response = urllib2.urlopen(req, json.dumps([p["firstname"] for p in Profiles]))
Upvotes: 4