我想用双引号替换此字符串字典中的所有单引号。

huangapple go评论54阅读模式
英文:

I want to replace all the single quotes in this string dict with double quotes

问题

请帮我将单引号替换为双引号,这样我可以调用json.loads将其转换为Python中的字典类型,以便提取键和值。下面的字典是以字符串格式表示的。

{"first_name": "John", "age": 89}

我不确定是否可以使用正则表达式或其他方法。请帮助我。

英文:

Please I want to replace the single quotes to double quotes so I can call json loads to convert it to a dictionary type in python so I can extract the keys and values. The dictionary below is in string format.

{'first_name': "John", "age": 89}

I don't know it regex is possible or any other method.
Please help me out

答案1

得分: 1

虽然您的示例字符串不是有效的 JSON但它对于 Python 字典来说是有效的因此您可以简单地使用 [`eval`](https://www.programiz.com/python-programming/methods/built-in/eval) [至少对于这个特定的字符串] 

```python
dictStr = '{'first_name': "John", "age": 89}'

dictObj = eval(dictStr)
print('dictObj:', type(dictObj), repr(dictObj), '\n')

# import json
jsonStr = json.dumps(eval(dictStr))
print('jsonStr:', type(jsonStr), repr(jsonStr), '\n')

应该输出

> python &gt; dictObj: <class 'dict'> {'first_name': 'John', 'age': 89} &gt; &gt; jsonStr: <class 'str'> '{"first_name": "John", "age": 89}' &gt; &gt;

jsonStr 恰好是您的标题所要求的,但我认为您的最终目标是 dictObj,您可能认为您需要 jsonStr [但在这种情况下您不需要它,因为您可以直接获得字典,而不需要修复 JSON。]


<details>
<summary>英文:</summary>

While your example string isn&#39;t valid JSON, it *is* valid for a python dictionary; so, you can get away with simply using [`eval`](https://www.programiz.com/python-programming/methods/built-in/eval) [at least for this particular string].

```python
dictStr = &#39;&#39;&#39;{&#39;first_name&#39;: &quot;John&quot;, &quot;age&quot;: 89}&#39;&#39;&#39;

dictObj = eval(dictStr)
print(&#39;dictObj:&#39;, type(dictObj), repr(dictObj), &#39;\n&#39;)

# import json
jsonStr = json.dumps(eval(dictStr))
print(&#39;jsonStr:&#39;, type(jsonStr), repr(jsonStr), &#39;\n&#39;)

should print

> python
&gt; dictObj: &lt;class &#39;dict&#39;&gt; {&#39;first_name&#39;: &#39;John&#39;, &#39;age&#39;: 89}
&gt;
&gt; jsonStr: &lt;class &#39;str&#39;&gt; &#39;{&quot;first_name&quot;: &quot;John&quot;, &quot;age&quot;: 89}&#39;
&gt;
&gt;

jsonStr is exactly what your title is asking for, but I think your end goal is dictObj which you probably though you need jsonStr for

huangapple
  • 本文由 发表于 2023年2月16日 08:21:17
  • 转载请务必保留本文链接:https://go.coder-hub.com/75466686.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定