parsing Special json in python

Viewed 52

I need help with parsing json in Python.

json example is:

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}'

How does this output convert to json? Or How to parse this json?

my code is :

import requests

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

What you shared is Python's representation of a bytes value - you can .decode() it and then pass it to json.loads if you import json.

This is probably what you're after, although you probably got that data from somewhere else that you can use instead of data:

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)

Result:

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

That's a dictionary, which you can then access as usual:

print(d['cluster_name'])

Result:

ElasticElastic

Note that, depending on the encoding of the bytes data you receive, .decode() may work, but if it doesn't it probably means the data is not encoded with the default 'utf-8' encoding Python uses and you'll need to tell the .decode() method what encoding to use instead.

Based on your comment, you need something like:

import json
import requests

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

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

print(d['cluster_name'])
Related