JSON中的空键值

发布于 2025-02-09 13:56:55 字数 458 浏览 3 评论 0原文

我正在尝试将字符串列表解析为JSON。当列表有项目时,退货是: {'Body':'{“ A”:“ A”,“ B”:[“ ABC”],“ C”:“ C”}}'' 使用json.dumps,然后使用JSON.LOADS奏效。

但是当列表为空时,返回是: {'Body':'{“ A”:“ A”,“ B”:,“ C”:“ C”}}}'

我获得jsondecodeerror:Expect value并且无法访问B键。

访问代码:b_key = []如果body.get(“ b”,[])==“” else json.dumps(body.get(“ b”,[]))

我知道它应该是“ b”:“”“ b”:[],但是我正在使用的平台返回空白值。

有办法解决这个问题吗?

I'm trying to parse a string list to JSON. When the list has items, the return is:
{'body': '{"A":"a", "B": ["abc"], "C":"c"}}'
Using json.dumps and then json.loads works out.

But when the list is empty, the return is:
{'body': '{"A":"a", "B": , "C": "c"}}'

I get a JSONDecodeError: Expecting value and can't access the B key.

Access code: B_key = [] if body.get("B", []) == "" else json.dumps(body.get("B", []))

I know that it should be "B": "" or "B": [] but the platform i'm working with returns the blank value.

Is there a way to solve this?

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

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

发布评论

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

评论(1

仄言 2025-02-16 13:56:55

由于您正在使用无效的JSON,因此需要在加载之前对其进行修复。

以下等级修复了您给出的示例中的示例 ([{{,] \ s*?” [^“]+” \ s*:)\ s*,

。您给出的是,它可能会与其他数据有关,解决此问题的方法正在解决产生无效JSON的任何内容。

import json
import re

invalid = '{"A":"a", "B": , "C": "c"}'

try:
    print(json.loads(invalid))
except json.JSONDecodeError as e:
    print(e)

valid = re.sub(r'([{,]\s*?"[^"]+"\s*:)\s*,', r'\1 null,', invalid)

print(json.loads(valid))  # {'A': 'a', 'B': None, 'C': 'c'}

Since you're working with invalid JSON, you'd need to fix it before loading it.

The following regex fixes the example you gave into valid json ([{,]\s*?"[^"]+"\s*:)\s*,.

NB. it is never a good idea fixing JSON with regexes and while this works with the example you gave, it might break with other data, the way to fix this is fixing whatever produces the invalid JSON.

import json
import re

invalid = '{"A":"a", "B": , "C": "c"}'

try:
    print(json.loads(invalid))
except json.JSONDecodeError as e:
    print(e)

valid = re.sub(r'([{,]\s*?"[^"]+"\s*:)\s*,', r'\1 null,', invalid)

print(json.loads(valid))  # {'A': 'a', 'B': None, 'C': 'c'}
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文