【问题标题】:How to access Value in a JSON string using a Key in Python?如何使用 Python 中的键访问 JSON 字符串中的值?
【发布时间】:2021-04-19 23:24:13
【问题描述】:

Python 代码:

import json
aaa='''
{
    "eee":"yes",
    "something": null,
    "ok": ["no","mmm","eee"],
    "please":false,
    "no": {"f":true,"h":"ttt"}
}
'''
data=json.loads(aaa)

当我这样做时:

print(len(data))

我得到了预期:

5

print(len(data['ok']))

给了

3

但不知何故

print(data[0])

给予

Traceback (most recent call last):
  File "file.py", line 34, in <module>
    print(data[0])
KeyError: 0

如何使用它的索引在这个 JSON 对象中获取一个术语?

【问题讨论】:

  • 索引需要一个列表。
  • 获得KeyError 的原因是因为您的dictionary 中没有0 作为密钥

标签: python arrays json string


【解决方案1】:

您询问了访问 JSON 中的位置,但 data 结构是 python dict,带有键和值,您可以只使用它的键来索引它,因为您做得很好data['ok'].

要获得 first 键,您可以首先获得 dict.items(),它是 key/value 对的列表,然后,因为它是 list,所以您可以使用 ints 进行索引

data.items()
# [('eee', 'yes'), ('something', None), ('ok', ['no', 'mmm', 'eee']), ('please', False), ('no', {'f': True, 'h': 'ttt'})]


items = list(data.items())
items[0]
# ('eee', 'yes')

【讨论】:

  • 虽然最新版本的 Python 保持 dict 键插入顺序,但在旧版本中不能保证。 Python 3.6 的 C 实现首先维护了 key order 作为实现细节,并且 order 在 Python 3.7 中是标准的。不要期望 3.6 的其他实现以及 3.5 及更早版本的任何实现都会为 item[0] 返回“eee”。
【解决方案2】:

Python 字典是无序的。这意味着您无法根据其索引值访问字典元素。您需要提供键来访问相应的值。

【讨论】:

  • Python 字典从 3.7 开始保持插入顺序。虽然它们不能被索引,但它们可以被迭代。
【解决方案3】:

这是你要找的吗?

您可以通过指定数据的Key 值来获取JSON 中的术语。这里,eeeKey

print((data['eee']))

将打印:

yes

同样,您可以使用其他Key 来获取它们各自的值。

JSON 数据格式为Key:Value

【讨论】:

    猜你喜欢
    • 2016-08-27
    • 1970-01-01
    • 2021-06-01
    • 1970-01-01
    • 1970-01-01
    • 2013-06-10
    • 1970-01-01
    • 2021-09-14
    • 1970-01-01
    相关资源
    最近更新 更多