0

I am using requests module. And, the data returned is unicode which contains the response(dictionary) from a server. Is there a way to pretty print the unicoded dictionary?

This response returned looks like this:

u'<<200:{"id":"12345","key_x":"41341e2277422","name":"xyz","key_y":"000566b8-1f52-5b38c","marked_for_removal":false,"max_capacity":3831609642556,"total_capacity":0,"total_reserved_capacity":0}'

or this:

u'>>GET https://x.x.x.x:8888/services/rest/abc : {'headers': {'content-type': 'application/json;charset=UTF-8', 'Accept': 'application/json, text/javascript, */*; q=0.01'}, 'params': {}, 'timeout': 30, 'verify': False}'

I want to print it in the following manner:

u'<<200:
{"id":"12345",
"key_x":"41341e2277422",
"name":"xyz",
"key_y":"000566b8-1f52-5b38c",
"marked_for_removal":false,
"max_capacity":3831609642556,
"total_capacity":0,
"total_reserved_capacity":0}'

i.e. the json, in between, should be formatted and the string can remain as it is.

I've tried converting data to string and printing it but that doesn't work.

import pprint
pprint.pprint(data.encode('utf-8'), width=1)
Aditya
  • 551
  • 5
  • 26

1 Answers1

1

response is of str type - contains the HTTP status code and actual JSON data structure.

import json
import pprint

# response is coming from requests, most likely Content-Type: text/plain 
# separate the status code '200' from the actual JSON data
status = response[:6]
data   = response[6:]

if '200' not in status:
   # Bail out, got an error
   exit(0)

parsed = json.loads(data.encode('utf-8'))

# Print output
print status
# Using pprint
pprint.pprint(parsed)
Joseph D.
  • 11,804
  • 3
  • 34
  • 67
  • 1
    the response in the question doesn't exactly look like valid json (there is the leading `'<<200:`) – avigil Mar 09 '18 at 06:57
  • @avigil, most likely that's the HTTP STATUS CODE. 200 OK, will update – Joseph D. Mar 09 '18 at 06:57
  • angry people :'( – avigil Mar 09 '18 at 07:08
  • Downvote probably because the `response.split(':')` is a list of too many values and throws too many values to unpack error – Aditya Mar 09 '18 at 07:13
  • But, your answer is specific to a very particular case. The response can be a huge string and somewhere a json in between. For eg. `u'>>GET https://x.x.x.x:8888/services/rest/abc : {'headers': {'content-type': 'application/json;charset=UTF-8', 'Accept': 'application/json, text/javascript, */*; q=0.01'}, 'params': {}, 'timeout': 30, 'verify': False}'` – Aditya Mar 09 '18 at 07:21
  • @Aditya haven't seen your update. questions like this should be very specific to have specific answers – Joseph D. Mar 09 '18 at 07:22
  • I'm upvoting this, seems like what the asker wanted. I think more information is needed about what kind of string may come before the JSON in order to split it more reliably. – Bemmu Mar 09 '18 at 07:31