如何在 json 文件中将浮点数组更改为整数数组

how to change float array into integers array in json file

    human_pose ='''{
    "annotations": [
        {
            "area": "356725",
            "image_id": "1",
            "iscrowd": "0",
            "category_id": "1",
            "keypoints": [
                371.5701271305881,
                188.86769422623237,
                2,
                380.9752835872622,
                174.5554996182501,
                2,
                353.4413472938106,
                177.5542451551607,
                2,
                397.6046906555844,
                184.91480238212299,
                2,
                328.49723669132726,
                196.90978452976526,
                2,
                478,
                258,
                2,
                302,
                285,
                2,
                577,
                287,
                1,
                343,
                390,
                2,
                661,
                282,
                2,
                431,
                363,
                2,
                430,
                486,
                1,
                352,
                477,
                2,
                416,
                662,
                2,
                335,
                643,
                2,
                329,
                785,
                2,
                307,
                810,
                2
            ]

        }]}'''

import json
import math


data = json.loads(human_pose)

for person in data['annotations']:
    key = person["keypoints"]
    [math.trunc(key) for key in key]

    #del person['area']

new_string = json.dumps(data)
print(new_string)


output:

{"annotations": [{"image_id": "1", "iscrowd": "0", "category_id": "1", "keypoints": [371.5701271305881, 188.86769422623237, 2, 380.9752835872622, 174.5554996182501, 2, 353.4413472938106, 177.5542451551607, 2, 397.6046906555844, 184.91480238212299, 2, 328.49723669132726, 196.90978452976526, 2, 478, 258, 2, 302, 285, 2, 577, 287, 1, 343, 390, 2, 661, 282, 2, 431, 363, 2, 430, 486, 1, 352, 477, 2, 416, 662, 2, 335, 643, 2, 329, 785, 2, 307, 810, 2]}]}

我正在尝试将关键点浮点值转换为整数,json.dumps 像我执行的那样保存更改 (del person['area']) 但不保存我在关键点上应用的更改。在 python 的 CLI 中,它将关键点显示为整数数组,但是当我将其转储到新的 json 文件时,更改不会被保存并保存为相同的原始文件。帮忙欣赏

您必须在转换数据后重新分配给定 json 中的关键点。

检查下面的代码:

for person in data['annotations']:
    key = person["keypoints"]
    person["keypoints"] = [math.trunc(k) for k in key]