You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Python中无法访问JSON响应里的float/int值问题求助

解决Python中JSON数值提取与字符串拼接的类型错误问题

问题分析

你碰到了两个关键问题:

  1. 遍历逻辑错误:你的JSON响应是单个字典结构,不是列表。for p in data:会遍历字典的键名(比如"method"、"params"),这时候p['method']必然报错——字符串没法用键来访问值。
  2. 类型拼接冲突:提取timing里的数值后,你试图用+把它和字符串'URL: '直接拼接,但Python不允许字符串与数值类型(Decimal/int/float)这样混合拼接,这就是你看到TypeError的根本原因。

解决方案

第一步:修正JSON数据的访问方式

因为你的JSON是单一字典,不需要循环,直接通过键层级访问即可:

from decimal import Decimal
import json

with open(file_) as json_file:
    data = json.load(json_file, parse_int=Decimal, parse_float=Decimal)
    # 直接判断method字段,无需循环
    if data["method"] == "Network.responseReceived":
        # 提取timing中的目标数值
        push_end_value = data['params']['response']['timing']['pushEnd']
        # 接下来处理数值与字符串的拼接

第二步:正确拼接字符串与数值

有三种简单有效的方法解决类型拼接问题:

方法1:使用f-string(Python 3.6+推荐)

f-string可以直接在字符串中嵌入变量,自动处理类型转换,代码最简洁:

print(f'pushEnd: {push_end_value}')
方法2:将数值转为字符串后拼接

用str()函数把数值类型转为字符串,再和其他字符串拼接:

print('pushEnd: ' + str(push_end_value))
方法3:利用print的多参数特性

print函数支持多个参数,会自动用空格分隔内容,完全不需要手动拼接:

print('pushEnd:', push_end_value)

完整修正后的代码示例

from decimal import Decimal
import json

file_ = "your_json_file.json"  # 替换为你的实际文件路径
with open(file_) as json_file:
    data = json.load(json_file, parse_int=Decimal, parse_float=Decimal)
    if data["method"] == "Network.responseReceived":
        timing = data['params']['response']['timing']
        # 批量打印多个timing字段示例
        print(f'connectEnd: {timing["connectEnd"]}')
        print(f'dnsStart: {timing["dnsStart"]}')
        print('pushEnd:', timing['pushEnd'])
        print('sendStart: ' + str(timing['sendStart']))

额外说明

如果你的JSON实际是包含多个Network.responseReceived条目的列表(比如[{"method": "...", ...}, {...}]),那循环逻辑要改为遍历列表元素:

with open(file_) as json_file:
    data_list = json.load(json_file, parse_int=Decimal, parse_float=Decimal)
    for p in data_list:
        if p["method"] == "Network.responseReceived":
            push_end_value = p['params']['response']['timing']['pushEnd']
            print(f'pushEnd: {push_end_value}')

内容的提问来源于stack exchange,提问作者MennoVanDeVlees

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.15 04:27:44