Im calling an API that gives the output in an array. This is the array data.
["{'meta':'projects/us/conf/94eb2c1f0574'}","{'del':'projects/us/conf/001a1143e726'}"]
Here I want to extract the value for the key meta.
projects/us/conf/94eb2c1f0574
How can I do this with Python? Also, the output is in correct array structure?
If you mean get the value where the key is meta you can use next
and a comprehension:
data = ["{'meta':'projects/us/conf/94eb2c1f0574'}","{'del':'projects/us/conf/001a1143e726'}"]
>>> next(v for (k, v) in map(dict.items, data) if k == 'meta')
projects/us/conf/94eb2c1f0574
Assuming this is array is loaded into the variable data
, data[0]
is the dictionary with one key 'meta'
. From there, you can access that key by passing the name.
>>> data = [{'meta':'projects/us/conf/94eb2c1f0574'}, {'del':'projects/us/conf/001a1143e726'}]
>>> data[0]['meta']
'projects/us/conf/94eb2c1f0574'
if your input is really looking like that (bad api design, or a bug in the API)
you can just load each as json
fixed = [json.loads(string_thing.replace("'",'"')) for string_thing in response_array]
>>> fixed[0]['meta']
u'projects/us/conf/94eb2c1f0574'
>>> fixed[1]['del']
u'projects/us/conf/001a1143e726'
if you wanted to make it one big dict
data = {}
for string_thing in response_array:
# this assumes the strings are valid json and always dicts
data.update(json.loads(string_thing.replace("'",'"')))
>>> data
{u'meta': u'projects/us/conf/94eb2c1f0574', u'del': u'projects/us/conf/001a1143e726'}
>>> data['meta']
u'projects/us/conf/94eb2c1f0574'
>>> data['del']
u'projects/us/conf/001a1143e726'
Quick fix would be to convert data[0] to a dict using json.loads -
value = json.loads(d[0].replace('\'','"'))['meta']
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.