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

4
我正在捕捉一个错误,但无法从返回的消息中提取我想要的内容。 以下是代码:
  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."}]

我想要提取msgpure_err_code,但是text并不是一个列表。[{ ... }]让我感到困惑。 response.text[0][response.text['msg'] 抛出了索引错误,所以它的行为就像一个字符串(据我所知)。

3个回答

4
你有 JSON数据。响应头甚至告诉你这一点:
'Content-Type': 'application/json'

使用 json 模块 解码此内容:
error_info = json.loads(response.text)

error_info 是一个列表,包含一个字典(这表明可能有0个或多个结果)。您可以循环遍历,也可以假设始终存在1个结果,在这种情况下,您可以使用 [0] 来提取仅该字典。

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

0

看起来你的response.text是一个JSON,所以首先解析它,然后访问你的数据:

import json

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

0

你的响应是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 - 它起作用了。我想那是我浪费的两个小时! - Ian Jones

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接