我正在使用MariaDB,不幸的是,json对象返回为字符串。我想将这些字符串化的json对象转换回json,但问题是-我只想在它们实际上是json对象时这样做,并且忽略所有字段,例如,只是普通字符串(但可以转换为json而不会导致错误)。
我的方法是检查字符串是否包含双引号,但这似乎有点太天真了,因为它也会转换一个自然包含双引号的字符串,但不打算作为json对象。有没有更健壮的方法来实现这一点?
import json
results = {"not_string": 1234,
"not_json": "1234",
"json": '[{"json": "1234"}]',
"false_positive": '["actually a quote in brackets"]'}
# load the json fields in the results
for key, value in results.items():
if isinstance(value, str) and '"' in value:
try:
results[key] = json.loads(value)
except Exception as e:
pass
for key, value in results.items():
print(type(value))
<class 'int'>
<class 'str'>
<class 'list'>
<class 'list'> <--
预期:
<class 'int'>
<class 'str'>
<class 'list'>
<class 'str'> <--
基本上,我不想依赖于“请求原谅”,因为字符串可以转换为json而不会导致错误,但这是一个假阳性,不应该这样做。
1条答案
按热度按时间8wigbo561#
我不知道你为什么要把false_positive转换成字符串,这是一个有效的列表。在这里我提供了一个解决方案,所有具有单个字符串值的列表都将转换成字符串。尝试以下代码:
这是输出: