Python(2.7.13)-我有一个看起来像数组的字符串

Python(2.7.13)-我有一个看起来像数组的字符串,python,string,list,Python,String,List,我正在捕获错误,但无法从返回的消息中提取所需内容。 代码如下: except purestorage.PureHTTPError as response: print "LUN Creation failed:" print dir(response) print "args:{}".format(response.args) print "code:{}".format(response.code) print "headers:{}".

我正在捕获错误,但无法从返回的消息中提取所需内容。 代码如下:

  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)
以下是输出:

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."}]
我想取出
msg
pure\u err\u code
,但是
文本
不是一个列表。
[{…}]
把我弄糊涂了。
response.text[0]
[
response.text['msg']
抛出一个索引错误,因此这就像一个字符串(afaIk)。

您已经知道了。响应头甚至告诉您:

'Content-Type': 'application/json'
使用以下命令对其进行解码:

error_info = json.loads(response.text)
error\u info
在本例中是一个包含单个词典的列表(表示可能有0个或多个结果)。您可以循环,或假设总是有1个结果,此时您可以使用
[0]
仅提取一个词典

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

您的
response.text
似乎是一个JSON,因此首先解析它,然后访问您的数据:

import json

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

您的响应是json,因此类似的内容将帮助您:

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

谢谢pyjg-它很有效。我想那是我生命中的两个小时,我再也回不来了!