简体   繁体   English

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

[英]Extract specific element from JSON in python

How do I print just the "name" through this JSON format? 如何通过这种JSON格式仅打印“名称”? in Python 2.7? 在python 2.7中? I've basically tried a lot of examples from stack overflow, but they're doing json.load and I am not sure if I need that if I already have a JSON as an output. 我基本上已经尝试了很多来自堆栈溢出的示例,但是它们正在执行json.load,如果我已经有一个JSON作为输出,我不确定是否需要。 I'm trying to trim it to only what I need. 我正在尝试将其调整为仅我需要的内容。 Any help would be great. 任何帮助都会很棒。 Thank you. 谢谢。

This is the example json and I only need the name PS: What is the 'u? 这是示例json,我只需要名称PS:'u是什么? I do not need that in my output. 我的输出中不需要它。

{  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},

assuming that that dict is assigned to some variable data you would just need to iterate the items and print the name for each one 假设将dict分配给某些变量data ,则只需要迭代这些项并为每个项打印名称

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

Your data is incomplete. 您的数据不完整。 Assuming you have the complete information, including valid JSON with appropriate block termination, you want to use json.load() to turn a str object (the JSON data is a string) into a dict . 假设您具有完整的信息,包括带有适当的块终止的有效JSON, json.load()使用json.load()str对象(JSON数据是字符串)转换为dict The u prefix denotes a Unicode string, which I think is not a valid JSON. u前缀表示Unicode字符串,我认为这不是有效的JSON。

Due to your observations, it appears that what you have is not JSON, but a dict (dictionary) object, and as such you might be looking for: 根据您的观察,看来您拥有的不是JSON,而是dict (字典)对象,因此您可能正在寻找:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM