Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/297.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 将值从字典中获取到JSON文件中_Python_Json_List_Dictionary - Fatal编程技术网

Python 将值从字典中获取到JSON文件中

Python 将值从字典中获取到JSON文件中,python,json,list,dictionary,Python,Json,List,Dictionary,我需要从此处显示的文件中获取所有bodyHtml和authorId值: 我尝试了几种方法,但我总是发现错误:TypeError:list索引必须是整数,而不是str 我尝试了几种方法,这是我最后的代码: # -*- coding: utf-8 -*- import json import requests import datetime data = json.loads(open('file.json').read()) coments = data['headDocument']['co

我需要从此处显示的文件中获取所有
bodyHtml
authorId
值:

我尝试了几种方法,但我总是发现错误:
TypeError:list索引必须是整数,而不是str

我尝试了几种方法,这是我最后的代码:

# -*- coding: utf-8 -*-
import json
import requests
import datetime

data = json.loads(open('file.json').read())

coments = data['headDocument']['content']['id']

for comment in data['headDocument']['content']['content']['bodyHtml']:
    info = comment
print(info)
并获取以下错误:

Traceback (most recent call last):
  File "coments.py", line 16, in <module>
    for comment in data['headDocument']['content']['content']['bodyHtml']:
TypeError: list indices must be integers, not str
回溯(最近一次呼叫最后一次):
文件“coments.py”,第16行,在
对于数据['headDocument']['content']['content']['bodyHtml']中的注释:
TypeError:列表索引必须是整数,而不是str

有人能帮你解决这个问题吗?

你的头文档['content']是一个列表,所以你应该循环浏览它。像这样:

for item in data['headDocument']['content']:
    print(item['content']['bodyHtml'])

您的headDocument['content']是一个列表,因此您应该循环浏览它。像这样:

for item in data['headDocument']['content']:
    print(item['content']['bodyHtml'])

某些对象没有
项['content']['bodyHtml']
键,脚本将为此返回一个错误。因此,您需要使用try/except语句捕获可能不存在的键的异常。某些对象没有
项['content']['bodyHtml']
键,您的脚本将为此返回一个错误。因此,您需要使用try/except语句来捕获可能不存在的键的异常。