【问题标题】:how to get Parameters from a json file with python如何使用python从json文件中获取参数
【发布时间】:2018-08-03 09:32:40
【问题描述】:

我正在 Python 中使用 JSON 文件。当我打印date 时,结果如下:

print (date['slot'])
[{'slot': 1, 'type': {'url': 'https://pokeapi.co/api/v2/type/11/', 'name': 
'water'}}]

但我只想得到'water'。我一直在使用不同的方法,但没有奏效。有人可以帮我从代码中获取 'water' 吗?

【问题讨论】:

  • date['slot'][0]["type"]['name'] ?
  • for d in data['slot']: print d['type']['name'] 这是您要找的吗?
  • 嗨 Madhan Varadhodiyil,它仍然一直这样说:for d in c ['slot']: TypeError: list indices must be integers or slices, not str
  • 嗨,Madhan Varadhodiyil,我只想得到名字:水

标签: python python-3.x python-requests


【解决方案1】:
print (date['slot'][0]['type']['name'])

print (date['slot'][0]['type']['name'] if date['slot'] else None)

或者更通用

for sd in date['slot']:
    print (sd['type']['name'])

【讨论】:

  • 嗨 Gaurav Jain,上面写着:for sd in c ['slot']: TypeError: list indices must be integers or slices, not str
  • 使用第二个选项说: print (c['slot'][0]['type']['name'] if c['slot'] else None) TypeError: list indices must是整数或切片,而不是 str >>>
  • c 是变量的名称,我将它从日期更改为 c
  • 试试c[0]['type']['name']
猜你喜欢
  • 2016-02-26
  • 2016-01-06
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2014-07-04
  • 1970-01-01
  • 2021-01-25
  • 2014-09-06
相关资源
最近更新 更多