【问题标题】:Get value from a dictionary into a JSON file从字典中获取值到 JSON 文件中
【发布时间】:2019-01-07 11:37:19
【问题描述】:

我需要从此处显示的文件中获取所有 bodyHtmlauthorId 值:https://drive.google.com/file/d/10EGOAWsw3G5-ETUryYX7__JPOfNwUsL6/view?usp=sharing

我尝试了好几种方法,但总是发现错误:TypeError: list indices must be integers, not 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

谁能帮忙解决这个问题?

【问题讨论】:

    标签: python json list dictionary


    【解决方案1】:

    您的 headDocument['content'] 是一个列表,因此您应该遍历它。像这样:

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

    【讨论】:

    • 某些对象没有item['content']['bodyHtml'] 键,您的脚本将为此返回错误。因此,您将需要使用 try/except 语句来捕获可能不存在的键的异常。
    猜你喜欢
    • 2021-09-16
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-01-02
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多