因此,此代码的结果是这样的列表:
[
{'id': 'abcd', 'created_time': '2016-12-09T13:45:43+0000'},
{'id': 'efgh', 'created_time': '2016-12-09T07:47:54+0000'},
{'id': 'ijkl', 'created_time': '2016-12-09T07:47:34+0000'},
{'id': 'mnop', 'created_time': '2016-12-09T07:47:09+0000'},
{'id': 'qrst', 'created_time': '2016-12-09T07:46:52+0000'}
]]
我希望得到一个列表:
ID
abcd
efgh
ijkl
mnop
qrst
我很感激任何帮助,因为我正用这个把头发拉出来!
def d_values(d, depth):
if depth == 1:
for i in d.values():
yield i
else:
for v in d.values():
if isinstance(v, dict):
for i in d_values(v, depth-1):
yield i
def Get_Message_IDs (Conversation_ID, Token):
Request = urllib.request.urlopen('https://graph.facebook.com/v2.8/' + Conversation_ID +'?fields=messages&access_token=' + Token)
ids = list()
try:
response = Request
output = response.read()
output = output.decode("utf-8")
output = ast.literal_eval(output)
output = list(d_values(output, 2))
print(output)
except Exception as exec:
print(exec)
答案 0 :(得分:1)
假设最后的额外]
是拼写错误,您的列表看起来像一个json列表。所以只需使用适当的json模块解析它(是的JSON语法和Python dict和列表看起来非常相似):
import json
# response is the result of your urllib.requests.urlopen(...)
my_list = json.loads(response.read().decode('utf-8'))
# then you can access the ids
print([element['id'] for element in my_list)
# if you want the exact output you mentioned in your question:
print("ID")
for element in my_list:
print(element.get('id'))
顺便说一下,我建议您使用外部requests
库而不是内置的urllib,它将解决远离您的JSON响应的所有痛苦:
import requests
response = requests.get('https://graph.facebook.com/v2.8/' + Conversation_ID +'?fields=messages&access_token=' + Token)
print(response.json())
答案 1 :(得分:0)
尝试:
l = # your list of dictionaries (json format)
[dic['id'] for dic in l]
输出:
['abcd', 'efgh', 'ijkl', 'mnop', 'qrst']
答案 2 :(得分:0)
ls = [
{'id': 'abcd', 'created_time': '2016-12-09T13:45:43+0000'},
{'id': 'efgh', 'created_time': '2016-12-09T07:47:54+0000'},
{'id': 'ijkl', 'created_time': '2016-12-09T07:47:34+0000'},
{'id': 'mnop', 'created_time': '2016-12-09T07:47:09+0000'},
{'id': 'qrst', 'created_time': '2016-12-09T07:46:52+0000'}
]
for d in ls:
if isinstance(d, dict):
print d['id']
abcd
efgh
ijkl
mnop
qrst