【问题标题】:Remove Python dict from JSON file response从 JSON 文件响应中删除 Python dict
【发布时间】:2015-12-28 17:48:04
【问题描述】:

我查看了以下一些资源:Remove python dict item from nested json file,但似乎无法让我的代码正常工作。根据我对下面我的 JSON 的理解(这是一个更长的转储的变量占位符),它是一个字典,里面有一个字典,里面有一个字典,里面有一个随机列表。我最终想看到的是我的终端的以下打印输出:

Message: [Client ID] 
Link: "http://linkgoeshere.com"

这是我目前所拥有的:

ThreeLine= {u'hits': {u'hits': [{u'_id': u'THIS IS THE FIRST ONE',
                  u'_index': u'foo',
                  u'_score': None,
                  u'_source': {u'@timestamp': u'2015-12-21T16:59:40.000-05:00',
                               u'message': u'Application.INFO: [Client ID ] Information Link: http://google.com {"check1":121212} {"tags":{"sent":"15","HTML":"5661"},"person":"15651"}',
                               u'system': u'user-info'}},
                {u'_id': u'THIS IS THE SECOND ONE',
                  u'_index': u'two',
                  u'_score': None,
                  u'_source': {u'@timestamp': u'2015-12-12 T16:59:40.000-05:00',
                               u'message': u'Application.INFO: [Client ID ] Information Link: http://google.com {"check1":565656} {"tags":{"sent":"21","HTML":"4512"},"person":"15651"}',
                               u'system': u'user-info'}},
]}}

unpacking= ThreeLine['hits']['hits'] #we only want to talk to the sort dictionary. 


for d in unpacking:
    newinfo= []
    narrow=[d["_source"] for d in unpacking if "_source" in d] 
    narrower=[d["message"] for d in narrow if "message" in d]
    newinfo.append(narrower)
print newinfo

现在,使用它的代码,它会打印两个条目,但它有很多我不关心的随机垃圾,就像所有标签一样:

{"tags":{"sent":"21","HTML":"4512"},"person":"15651"}',

那么,我如何进一步去除这些条目,以便最终得到我最终想要摆脱这种疯狂嵌套的混乱的两行?如果有人对我如何清理当前代码有任何想法,我会全力以赴并准备好学习!

【问题讨论】:

    标签: python json dictionary


    【解决方案1】:

    “标签”字典不是字典。它是嵌入在消息字符串中的文本

    >>> ThreeLine['hits']['hits'][0]['_source']['message']
    u'Application.INFO: [Client ID ] Information Link: http://google.com {"check1":121212} {"tags":{"sent":"15","HTML":"5661"},"person":"15651"}'
    

    您必须进行一些字符串解析才能删除它。您可以使用正则表达式:

    import re
    id_and_link = re.compile(r'(\[[^]]+\]) Information Link: (https?://[\w\d/.]+)')
    
    messages = (entry['_source']['message'] for entry in ThreeLine['hits']['hits'] if '_source' in entry and 'message' in entry['_source'])
    for message in messages:
        match = id_and_link.search(message)
        if not match:
            continue
        id_, link = match.groups()
        print 'Message:', id_
        print 'Link:', link
        print
    

    【讨论】:

    • 嗯,这并没有给我任何东西。任何想法为什么?
    • @SamW:可能是因为您的 real 数据略有不同,因此正则表达式不匹配。给我们一些真实的message 值,而不是弥补问题。
    • 我明白了,星期一的大脑。 :) 非常感谢!
    猜你喜欢
    • 2015-04-26
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-10-20
    • 2017-04-24
    • 1970-01-01
    • 2021-12-22
    • 1970-01-01
    相关资源
    最近更新 更多