Python (2.7.13) - I have a string that looks like an array

I am delaying the error but cannot extract what I want from the returned message. Here is the code:

  except purestorage.PureHTTPError as response:
     print "LUN Creation failed:"

     print dir(response)
     print "args:{}".format(response.args)
     print "code:{}".format(response.code)
     print "headers:{}".format(response.headers)
     print "message:{}".format(response.message)
     print "reason:{}".format(response.reason)
     print "rest_version:{}".format(response.rest_version)
     print "target:{}".format(response.target )
     print "text:{}".format(response.text)

Here's the conclusion:

LUN Creation failed:
['__class__', '__delattr__', '__dict__', '__doc__', '__format__', '__getattribute__', '__getitem__', '__getslice__', '__hash__', '__init__', '__module__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__setattr__', '__setstate__', '__sizeof__', '__str__', '__subclasshook__', '__unicode__', '__weakref__', 'args', 'code', 'headers', 'message', 'reason', 'rest_version', 'target', 'text']
args:()
code:400
headers:{'Content-Length': '113', 'Set-Cookie': 'session=....; Expires=Wed, 05-Jul-2017 16:28:26 GMT; HttpOnly; Path=/', 'Server': 'nginx/1.4.6 (Ubuntu)', 'Connection': 'keep-alive', 'Date': 'Wed, 05 Jul 2017 15:58:26 GMT', 'Content-Type': 'application/json'}
message:
reason:BAD REQUEST
rest_version:1.8
target:array1
text:[{"pure_err_key": "err.friendly", "code": 0, "ctx": "lun-name", "pure_err_code": 1, "msg": "Volume already exists."}]

I want to pull msgand pure_err_code, but is textnot a list. [{ ... }]bothers me. response.text[0] [and response.text['msg']throws an index error, so it acts like a string (afaIk).

+4
source share
3 answers

You have JSON data . The response headers even tell you the following:

'Content-Type': 'application/json'

Use jsonmodule to decode this:

error_info = json.loads(response.text)

error_info - , (, 0 ). , 1 , [0]

print(error_info[0]['pure_err__key'])
print(error_info[0]['msg'])
+4

, response.text JSON, :

import json

data = json.loads(response.text)
print(data[0]["pure_err_code"])
print(data[0]["msg"])
# etc.
0

Your answer is json, so something like this will help you:

import json

a = '[{"pure_err_key": "err.friendly", "code": 0, "ctx": "lun-name", "pure_err_code": 1, "msg": "Volume already exists."}]'

h = json.loads(a)

print(h[0]['code']) #prints 0
0
source

Source: https://habr.com/ru/post/1680814/


All Articles