mariadb 将字符串化的JSON对象转换为JSON

bksxznpy  于 2023-03-23  发布在  其他
关注(0)|答案(1)|浏览(127)

我正在使用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而不会导致错误,但这是一个假阳性,不应该这样做。

8wigbo56

8wigbo561#

我不知道你为什么要把false_positive转换成字符串,这是一个有效的列表。在这里我提供了一个解决方案,所有具有单个字符串值的列表都将转换成字符串。尝试以下代码:

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:
            temp = json.loads(value)
            if isinstance(temp, list):
                if len(temp) == 1 and isinstance(temp[0], str):
                    results[key] = temp[0]
                else:
                    results[key] = temp
        except Exception as e:
            pass
for key, value in results.items():
    print(type(value))
    
print(results)

这是输出:

<class 'int'>
<class 'str'>
<class 'list'>
<class 'str'>
{'not_string': 1234, 'not_json': '1234', 'json': [{'json': '1234'}], 'false_positive': 'actually a quote in brackets'}

相关问题