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

Python中如何从JSON数据的result字段提取SafeGasPrice字符串值

提取嵌套字段SafeGasPrice的实现方法

首先明确数据层级:你需要的字段位于根对象下result嵌套对象内,当前样例中该字段的字符串值为119。

注意:你贴出的原始内容使用单引号包裹键和值,不符合标准JSON语法要求,解析前如果是字符串格式,需要先将单引号替换为双引号,否则标准JSON解析器会抛出格式错误。

不同语言的实现示例

  • Python 环境

    1. 数据已经解析为字典结构时,直接按键逐层索引取值即可:
    # resp 为接口返回的已解析字典
    resp = {'status': '1', 'message': 'OK',
    'result': {'LastBlock': '14934113', 'SafeGasPrice': '119', 'ProposeGasPrice': '119', 'FastGasPrice': '119',
    'suggestBaseFee': '118.174590189', 'gasUsedRatio': '0.025821954106323,0.354559890356924,0.173050329701518,0.340210087647076,0.0269005272339711'}}
    
    safe_gas_price = resp['result']['SafeGasPrice']
    # 取值结果为字符串 '119'
    
    1. 拿到的是原始字符串时,先修正格式再解析:
    import json
    raw_content = """{'status': '1', 'message': 'OK','result': {'LastBlock': '14934113', 'SafeGasPrice': '119', 'ProposeGasPrice': '119', 'FastGasPrice': '119','suggestBaseFee': '118.174590189', 'gasUsedRatio': '0.025821954106323,0.354559890356924,0.173050329701518,0.340210087647076,0.0269005272339711'}}"""
    # 替换单引号为双引号,转为标准JSON格式
    standard_json = raw_content.replace("'", '"')
    resp = json.loads(standard_json)
    safe_gas_price = resp['result']['SafeGasPrice']
    
  • JavaScript 环境
    数据解析为对象后,直接通过属性访问取值:

    // 若为原始JSON字符串,先替换单引号再执行 JSON.parse 转成对象
    const resp = JSON.parse(rawStr.replaceAll("'", '"'))
    const safeGasPrice = resp.result.SafeGasPrice
    // 取值结果为字符串 "119"
    

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.30 10:39:19