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

如何用Python修改JSON文件,将数值保留小数点后两位?

处理JSON中多位小数保留两位的方法

Python实现

这是最灵活的方案,适合需要自定义处理逻辑的场景:

核心思路

读取JSON数据后,遍历需要处理的字段,将字符串格式的数值转为浮点数,保留两位小数后再转回字符串(也可直接存为数字类型),非数值内容原样保留。

示例代码:

import json

def format_decimal(val):
    try:
        num = float(val)
        # 整数保持原格式,小数保留两位
        if num.is_integer():
            return str(int(num))
        return "{:.2f}".format(num)
    except (ValueError, TypeError):
        # 非数值类型直接返回原值
        return val

def process_json(data):
    for food in data["JSON_DATA"]:
        # 处理顶层营养数值字段
        for field in ["kcal", "carb", "protein", "fat"]:
            if field in food:
                food[field] = format_decimal(food[field])
        # 处理每个单位下的详细营养数据
        for unit in food["units"]:
            for key, val in unit.items():
                unit[key] = format_decimal(val)
    return data

# 读取原始JSON文件
with open("input.json", "r", encoding="utf-8") as f:
    raw_data = json.load(f)

# 处理数据
processed_data = process_json(raw_data)

# 写入处理后的JSON文件
with open("output.json", "w", encoding="utf-8") as f:
    json.dump(processed_data, f, indent=2, ensure_ascii=False)

命令行工具jq(无需编写代码)

如果熟悉命令行,用jq可以快速完成批量处理,适合简单场景:

jq '.JSON_DATA[] |= (
    .kcal |= (tonumber | (if . == floor(.) then tostring else . | round(2) | tostring end)),
    .carb |= (tonumber | (if . == floor(.) then tostring else . | round(2) | tostring end)),
    .protein |= (tonumber | (if . == floor(.) then tostring else . | round(2) | tostring end)),
    .fat |= (tonumber | (if . == floor(.) then tostring else . | round(2) | tostring end)),
    .units[] |= with_entries(
        .value |= (tonumber? // . | (if . == floor(.) then tostring else . | round(2) | tostring end))
    )
)' input.json > output.json

这段命令会自动识别所有可转换为数值的字段,保留两位小数的同时,避免把整数转为x.00格式。

可选调整

  • 若希望将数值以数字类型(而非字符串)保存,只需把"{:.2f}".format(num)替换为round(num, 2)即可。
  • 代码会自动跳过"null"这类非数值字符串,保持原始内容不变。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.09 08:30:47