python - 如何使用 Python 中的键访问 JSON 字符串中的值?

标签 python arrays json string

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 对象中的术语?

最佳答案

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

要获取 first 键,您可以先获取 dict.items(),它是 key/value 对的列表,然后,因为它是一个列表,你可以用整数索引

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 - 如何使用 Python 中的键访问 JSON 字符串中的值?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/65727499/

相关文章:

php - 内爆数组与电子邮件一起使用时出错

javascript - Ajax 请求返回 200 OK,但触发了错误事件而不是成功

python - 如何使用 Python 打开 Unix 可执行文件?

python - 零除法错误: float division by zero (Solving colebrook (nonlinear) equation with Newton Raphson method in python)

python - python中的随机列表选择

Python - 如何跳过特定的 JSON 元素?

java - 无法让 MappedSuperClass 抽象实体与 Spring Boot 和 JPA 一起使用

python - 是否可以使用一个整体 rate_func 运行多个动画?

c++ - C int 到 char 转换添加了垃圾字符

javascript - 如何在 angularjs 中迭代 $scope 变量?