英文:
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 > dictObj: <class 'dict'> {'first_name': 'John', 'age': 89} > > jsonStr: <class 'str'> '{"first_name": "John", "age": 89}' > >
jsonStr
恰好是您的标题所要求的,但我认为您的最终目标是 dictObj
,您可能认为您需要 jsonStr
[但在这种情况下您不需要它,因为您可以直接获得字典,而不需要修复 JSON。]
<details>
<summary>英文:</summary>
While your example string isn'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 = '''{'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')
should print
> python
> dictObj: <class 'dict'> {'first_name': 'John', 'age': 89}
>
> jsonStr: <class 'str'> '{"first_name": "John", "age": 89}'
>
>
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
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论