我怎样用Python编辑json文件中的点后有2位数?

bnl4lu3b  于 2022-12-15  发布在  Python
关注(0)|答案(2)|浏览(163)
{
  "JSON_DATA": [
    {
      "id": 0,
      "name": "Name",
      "image": "food_0.jpg",
      "kcal": "32",
      "url": "bat",
      "desc": "null",
      "time": "null",
      "first_unit": "Unit1",
      "carb": "72",
      "protein": "23",
      "fat": "4",
      "units": [
        {
          "unit": "Unit1",
          "amount": "15.0000",
          "calory": "32.4877372383",
          "carbohydrt": "5.44751985283",
          "protein": "1.75822099387",
          "fat": "0.155740956864",
          "calcium": "8.71466176412",
          "cholestrl": "0.0",
          "fiber_td": "1.85840511552",
          "iron": "0.711263854542",
          "lipid_tot": "0.155740956864",
          "potassium": "87.793890567",
          "sodium": "15.666368442",
          "vit_a_iu": "11.8943218304",
          "vit_c": "2.25616660116"
        },
        {
          "unit": "Unit2",
          "amount": "110.0000",
          "calory": "238.243406414",
          "carbohydrt": "39.9484789208",
          "protein": "12.8936206218",
          "fat": "1.14210035034",
          "calcium": "63.9075196035",
          "cholestrl": "0.0",
          "fiber_td": "13.6283041805",
          "iron": "5.21593493331",
          "lipid_tot": "1.14210035034",
          "potassium": "643.821864158",
          "sodium": "114.886701908",
          "vit_a_iu": "87.2250267561",
          "vit_c": "16.5452217418"
        },
        {
          "unit": "Unit3",
          "amount": "1.0000",
          "calory": "2.16584914922",
          "carbohydrt": "0.363167990189",
          "protein": "0.117214732925",
          "fat": "0.0103827304576",
          "calcium": "0.580977450941",
          "cholestrl": "0.0",
          "fiber_td": "0.123893674368",
          "iron": "0.0474175903028",
          "lipid_tot": "0.0103827304576",
          "potassium": "5.8529260378",
          "sodium": "1.0444245628",
          "vit_a_iu": "0.792954788692",
          "vit_c": "0.150411106744"
        }
      ]
    }
  ]
}

你好,我有这样一个json文件,这个json数据之间有很长的逗号数字,我想编辑一下,比如我想把Unit1对象中calory键的值32. 4877372383保存为32. 48。
我怎么用Python来做这个呢?或者我还能用什么其他的方法来做呢?我只想在点后面剩下2位数。

lskq00tm

lskq00tm1#

import json

with open("data.json", "r") as jsonFile:
    data = json.load(jsonFile)

dicts_list = data["JSON_DATA"][0]["units"]
for i, d in enumerate(dicts_list):
    for k, v in dicts_list[i].items():
        if '.' in v:
            dicts_list[i][k] = '.'.join(((v.split(".")[0], v.split(".")[1][:2])))
        
with open("modified_data.json", "w") as jsonFile:
    json.dump(data, jsonFile, indent=4)
yduiuuwa

yduiuuwa2#

您可以使用此方法

print("{:.2f}".format(32.4877372383))

您可以将2f中的2更改为想要显示的任意小数点位数。

相关问题