【问题标题】:Parsing JSON (String v Int indices)解析 JSON(String v Int 索引)
【发布时间】:2022-12-15 03:27:02
【问题描述】:

我会尽量简洁地解释这个问题。我正在尝试从来自 Elastic 的日志文件中过滤一些值。日志准确输出此 JSON:

{'took': 2, 'timed_out': False, '_shards': {'total': 1, 'successful': 1, 'skipped': 0, 'failed': 0}, 'hits': {'total': {'value': 2, 'relation': 'eq'}, 'max_score': None, 'hits': [{'_index': 'winlogbeat-dc-2022.10.17-000014', '_type': '_doc', '_id': 'vOCnfoQBeS2JF7giMG9q', '_score': None, '_source': {'agent': {'hostname': 'SRVDC1'}, '@timestamp': '2022-11-16T04:19:13.622Z'}, 'sort': [-9223372036854775808]}, {'_index': 'winlogbeat-dc-2022.10.17-000014', '_type': '_doc', '_id': 'veCnfoQBeS2JF7giMG9q', '_score': None, '_source': {'agent': {'hostname': 'SRVDC1'}, '@timestamp': '2022-11-16T04:19:13.630Z'}, 'sort': [-9223372036854775808]}]}}

现在,我只想过滤掉_指数@时间戳键。如果我将这个 JSON 分配给一个变量,我可以通过运行完美地过滤掉这两个键:

index = (data['hits']['hits'][0]['_index'])
timestamp = (data['hits']['hits'][0]['_source']['@timestamp'])

输出:

winlogbeat-dc*
2022-11-16T04:19:13.622Z

但是,如果我尝试直接从服务器调用中执行相同的操作,我会得到:

Traceback (most recent call last):
  File "c:\Users\user\Desktop\PYTHON\tiny2.py", line 96, in <module>
    query()
  File "c:\Users\user\Desktop\PYTHON\tiny2.py", line 77, in query
    index = (final_data['hits']['hits'][0]['_index'])
TypeError: string indices must be integers

现在,我明白它要求的是整数值而不是我正在使用的字符串,但是如果我使用整数,那么我得到的是单个字符而不是键/值对。

我错过了什么?

【问题讨论】:

  • 向我们展示实际代码。您可能错过了字符串的反序列化
  • 你检查过final_data['hits']['hits'][0]了吗?我认为这是字符串值。

标签: python


【解决方案1】:

也许您必须先将字符串解析为 json 对象:

import json
final_data = json.loads("json-string-from-es")
index = final_data['hits']['hits'][0]['_index']

我不确定为什么要用括号括起索引选择。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2015-06-24
    • 2022-07-29
    • 2013-08-27
    • 1970-01-01
    • 2018-08-06
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多