从python中的JSON中提取特定元素

2024-03-28 12:21:36 发布

您现在位置:Python中文网/ 问答频道 /正文

如何通过这个JSON格式打印“name”?在Python2.7中? 我基本上已经尝试过很多堆栈溢出的例子,但是它们都在做json.load文件如果已经有一个JSON作为输出,我不确定是否需要它。我试着把它裁剪成我需要的。任何帮助都会很好。非常感谢。在

这是json示例,我只需要名称 PS:什么是u?我的输出不需要这个。在

{  u'data': {  u'items': [  {  u'created_at': 1401991208,
                           u'name': u'Great Deals Singapore',
                           u'path': u'organization/great-deals-singapore',
                           u'type': u'Organization',
                           u'updated_at': 1442343527},
                        {  u'created_at': 1415172261,
                           u'name': u'Secure Tech Alarm Systems Inc.',
                           u'path': u'organization/secure-tech-alarm-systems-inc-',
                           u'type': u'Organization',
                           u'updated_at': 1432082588},
                        {  u'created_at': 1307858564,
                           u'name': u'Foodcaching',
                           u'path': u'organization/foodcaching',
                           u'type': u'Organization',
                           u'updated_at': 1406611074},
                        {  u'created_at': 1421406244,
                           u'name': u'WP App Store',
                           u'path': u'organization/wp-app-store',
                           u'type': u'Organization',
                           u'updated_at': 1421406364},

Tags: 文件pathnamejson堆栈格式typeload
2条回答

你的数据不完整。假设您有完整的信息,包括带有适当块终止的有效JSON,您希望使用json.load()str对象(JSON数据是字符串)转换为dictu前缀表示Unicode字符串,我认为它不是有效的JSON。在

根据您的观察,您得到的不是JSON,而是一个dict(dictionary)对象,因此您可能会寻找:

for item in your_dict['data']['items']:
    print item['name']

假设dict被分配给某个变量data,那么您只需要迭代这些项并打印每个项的名称

for item in data['items']:
    print item['name']

相关问题 更多 >