我需要在 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/