当某些值包含单引号时将字符串加载到字典中

发布于 2025-01-21 01:56:56 字数 1067 浏览 0 评论 0原文

我有一个需要加载到字典中的字符串。我正在尝试使用json.loads()来执行此操作,但是它失败了,因为我需要用双引号替换单个报价,尽管在某些情况下,该值包裹在双引号中,因为它包含一个引用。

这是使用Python3.8的可复制示例,

>>> import json
>>> example = "{'msg': \"I'm a string\"}"
>>> json.loads(example.replace("'", '"'))
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "/usr/local/lib/python3.8/json/__init__.py", line 357, in loads
    return _default_decoder.decode(s)
  File "/usr/local/lib/python3.8/json/decoder.py", line 337, in decode
    obj, end = self.raw_decode(s, idx=_w(s, 0).end())
  File "/usr/local/lib/python3.8/json/decoder.py", line 353, in raw_decode
    obj, end = self.scan_once(s, idx)
json.decoder.JSONDecodeError: Expecting ',' delimiter: line 1 column 12 (char 11)

有没有更好的方法将字符串加载到字典中? JSON模块似乎仅适用于双引号,因此在这里不可能(我无法控制字符串的格式),因此为什么我必须使用不可靠的替换

我期望的结果是要有这样的词典。

{'msg': "I'm a string"}

I have a string that I need to load into a dictionary. I'm trying to use json.loads() to do this, but it is failing because I need to replace single quotes with double quotes because by default the strings use single quotes to wrap property names and values, although in some cases the value is wrapped in double quotes because it contains an single quote.

Here is a reproduceable example using Python3.8

>>> import json
>>> example = "{'msg': \"I'm a string\"}"
>>> json.loads(example.replace("'", '"'))
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "/usr/local/lib/python3.8/json/__init__.py", line 357, in loads
    return _default_decoder.decode(s)
  File "/usr/local/lib/python3.8/json/decoder.py", line 337, in decode
    obj, end = self.raw_decode(s, idx=_w(s, 0).end())
  File "/usr/local/lib/python3.8/json/decoder.py", line 353, in raw_decode
    obj, end = self.scan_once(s, idx)
json.decoder.JSONDecodeError: Expecting ',' delimiter: line 1 column 12 (char 11)

Is there a better way to load a string into a dictionary? The json module seems to only work with double quotes and as that is not possible here (I have no control over the formatting of the strings), hence why I'm having to use the unreliable replace.

My desired result is to have a dictionary like this.

{'msg': "I'm a string"}

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

§对你不离不弃 2025-01-28 01:56:56

使用 ast.literal_eval()文档

>>> import ast
>>> ast.literal_eval(example)

 {'msg': "I'm a string"}

Use ast.literal_eval()Docs:

>>> import ast
>>> ast.literal_eval(example)

 {'msg': "I'm a string"}
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文