繁体   English   中英

努力将字符串转换为 python 中的字典

[英]Struggling to convert string to Dict in python

我正在使用boto3进行ssm调用。 我这样打电话。

import boto3
import json
ssm = boto3.client("ssm")
ssm.get_parameter(Name="slack_webhook")["Parameter"]["Value"]

我得到的响应是一个看起来像这样的字符串文本。

'Value\n{\n"progress-updates":  "https://hooks.slack.com/services/T0JExxxU6A6Q/xxxxxxxxx/pS7FvL1bIGZggKhLQvWsLAcV",\n"test-channel": "https://hooks.slack.com/services/xxxxxx/xxxxxxxx/IXnWw4sLN5GjI324glzfUIdM",\n"prod": "https://hooks.slack.com/services/xxxx/xxxxx/xgtsgdgsdgsdgdsgs"\n}'

所以当我执行以下操作时

json.loads(ssm.get_parameter(Name="slack_webhook")["Parameter"]["Value"])

我收到以下错误

JSONDecodeError Traceback(最近一次调用)在 ----> 1 json.loads(ssm.get_parameter(Name="slack_webhook")["Parameter"]["Value"])

/usr/local/Caskroom/miniconda/base/envs/pipeline/lib/python3.7/json/ init .py in loads(s, encoding, cls, object_hook, parse_float, parse_int, parse_constant, object_pairs_hook, **kw) 346 parse_int 是 None,parse_float 是 None,347 parse_constant 是 None,object_pairs_hook 是 None,不是 kw): --> 348 return _default_decoder.decode(s) 349 if cls is None: 350 cls = JSONDecoder

/usr/local/Caskroom/miniconda/base/envs/pipeline/lib/python3.7/json/decoder.py in decode(self, s, _w) 335 336 """ --> 337 obj, end = self. raw_decode(s, idx=_w(s, 0).end()) 338 end = _w(s, end).end() 339 如果end:= len(s):

/usr/local/Caskroom/miniconda/base/envs/pipeline/lib/python3.7/json/decoder.py in raw_decode(self, s, idx) 353 obj, end = self.scan_once(s, idx) 354 除了StopIteration as err: --> 355 raise JSONDecodeError("Expecting value", s, err.value) from None 356 return obj, end

JSONDecodeError:预期值:第 1 行第 1 列(字符 0)

我非常感谢在这件事上的帮助。 我是否需要通过删除所有\n来进一步清理字符串? 因为我试过了,也没有用。

它失败是因为领先的Value 假设Value字符串是响应的一部分,您可以编写一个简单的 function 来修剪前导键:

def parse_json(x):
    first_brace = x.find("{")
    if first_brace == -1:
        raise ValueError(f"Does not look like a JSON: {x}")
    x = x[first_brace:]
    return json.loads(x)


>>> parse_json(x)
{'progress-updates': 'https://hooks.slack.com/services/T0JExxxU6A6Q/xxxxxxxxx/pS7FvL1bIGZggKhLQvWsLAcV',
 'test-channel': 'https://hooks.slack.com/services/xxxxxx/xxxxxxxx/IXnWw4sLN5GjI324glzfUIdM',
 'prod': 'https://hooks.slack.com/services/xxxx/xxxxx/xgtsgdgsdgsdgdsgs'}

这是响应中包含的有效字符串 JSON。

'{
"progress-updates":"https://hooks.slack.com/services/T0JExxxU6A6Q/xxxxxxxxx/pS7FvL1bIGZggKhLQvWsLAcV",
"test-channel":"https://hooks.slack.com/services/xxxxxx/xxxxxxxx/IXnWw4sLN5GjI324glzfUIdM",
"prod": "https://hooks.slack.com/services/xxxx/xxxxx/xgtsgdgsdgsdgdsgs"
}'

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM