python - 在python中解析特殊的json

标签 python json elasticsearch

我需要在 Python 中解析 json 的帮助。

json 示例是:

b'{"cluster_name":"ElasticElastic","status":"green","timed_out":false,"number_of_nodes":1,"number_of_data_nodes":1,"active_primary'
b'_shards":397,"active_shards":397,"relocating_shards":0,"initializing_shards":0,"unassigned_shards":0,"delayed_unassigned_shards"'
b':0,"number_of_pending_tasks":0,"number_of_in_flight_fetch":0,"task_max_waiting_in_queue_millis":0,"active_shards_percent_as_numb'
b'er":100.0}'

这个输出如何转换为 json?或者如何解析这个json?

我的代码是:

import requests

res = requests.get("http://localhost:8200/_cluster/health")
for i in res :
    print(i)

最佳答案

您分享的是Python对字节值的表示 - 如果您导入json,您可以.decode()它,然后将其传递给json.loads .

这可能就是您想要的,尽管您可能从其他地方获得了可以使用的数据来代替数据:

import json

data = b'{"cluster_name":"ElasticElastic","status":"green","timed_out":false,"number_of_nodes":1,"number_of_data_nodes":1,"active_primary' \
       b'_shards":397,"active_shards":397,"relocating_shards":0,"initializing_shards":0,"unassigned_shards":0,"delayed_unassigned_shards"' \
       b':0,"number_of_pending_tasks":0,"number_of_in_flight_fetch":0,"task_max_waiting_in_queue_millis":0,"active_shards_percent_as_numb' \
       b'er":100.0}'

d = json.loads(data.decode())

print(d)

结果:

{'cluster_name': 'ElasticElastic', 'status': 'green', 'timed_out': False, 'number_of_nodes': 1, 'number_of_data_nodes': 1, 'active_primary_shards': 397, 'active_shards': 397, 'relocating_shards': 0, 'initializing_shards': 0, 'unassigned_shards': 0, 'delayed_unassigned_shards': 0, 'number_of_pending_tasks': 0, 'number_of_in_flight_fetch': 0, 'task_max_waiting_in_queue_millis': 0, 'active_shards_percent_as_number': 100.0}

这是一本字典,您可以像往常一样访问它:

print(d['cluster_name'])

结果:

ElasticElastic

请注意,根据您收到的 bytes 数据的编码,.decode() 可能会起作用,但如果不起作用,则可能意味着数据是未使用 Python 使用的默认 'utf-8' 编码进行编码,您需要告诉 .decode() 方法要使用什么编码。

根据您的评论,您需要如下内容:

import json
import requests

res = requests.get("localhost:8200/_cluster/health")
data = res.content

d = json.loads(data.decode())

print(d['cluster_name'])

关于python - 在python中解析特殊的json,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/70515886/

相关文章:

java - Intershop 构建 url 并从管道访问语言属性文件

json - 不同类型反射的 Golang JSON 数组 : float64 vs int64

elasticsearch - 重新索引而无需定义别名

java - 使用优先级队列从值列表中获取n个排序元素(分页)

python - pymongo类型错误: document must be an instance of dict, bson.son.SON,bson.raw_bson.RawBSONDocument

Python 正则表达式与 split 方法

python - 字符串 split() 的身份怪癖

python - Django views.py 从基于类的 View 中的类别选择更新分页

html - 了解 Perl 中的 JSON-RPC

docker - 导入所有数据后自动停止Logstash进程