【问题标题】:JSON JSONDecodeError: Extra data PythonJSON JSONDecodeError:额外数据 Python
【发布时间】:2020-11-21 22:42:32
【问题描述】:

我正在尝试使用 Python 打印 Json 的每个值。 有 3 个由“,”分隔的 Json 短语,如果我尝试将所有短语加载到 json.loads 函数中,则会出现错误。

这是我想要做的:

x = '{"level": 1, "body": "hey", "track": 199}, {"level": 2, "body": "good", "track": 199}, {"level": 3, "body": "nice", "track": 199}, {"level": 4, "body": "thin", "track": 199}'
y = json.loads(x)

以及我得到的错误:

json.decoder.JSONDecodeError:额外数据:第 1 行第 55 列(字符 54)

我让它工作的唯一方法是获取该字符串中的每个 json 短语并对其使用 json.loads() 函数。

所以

x = '{"level": 1, "body": "hey", "track": 199}'
y = json.loads(x) # this does work but how do I split the string to these phrases?

【问题讨论】:

    标签: python json


    【解决方案1】:

    JSON 字符串的顶层必须只是一个数组或对象。如果你想拥有多个对象,它们必须在一个数组中。

    x = '[{"level": 1, "body": "hey", "track": 199}, {"level": 2, "body": "good", "track": 199}, {"level": 3, "body": "nice", "track": 199}, {"level": 4, "body": "thin", "track": 199}]'
    

    当你加载这个时,你会得到一个字典列表。

    【讨论】:

      猜你喜欢
      • 2021-04-04
      • 2021-09-13
      • 2021-06-28
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-07-05
      相关资源
      最近更新 更多