Python 在json中将浮点字符串转换为浮点

Python 在json中将浮点字符串转换为浮点,python,json,Python,Json,我有一个json(test.json)文件,其中包含以下数据。我有大约10000张唱片。我需要在新文件(test1.json)中将value从字符串转换为float write。如何从Python中执行此操作 { "name":"test001", "cat":"test", "loc":"x loc", "ings":[

我有一个json(
test.json
)文件,其中包含以下数据。我有大约10000张唱片。我需要在新文件(
test1.json
)中将
value
从字符串转换为float write。如何从Python中执行此操作

{
    "name":"test001",
    "cat":"test",
    "loc":"x loc",
    "ings":[
        {
            "name":"rrrrrr",
            "value":"13.0"
        },
        {
            "name":"hhhh",
            "value":"18.0"
        }
    ],
    "nums":[
        {
            "name":"kkkk",
            "value":"82.05"
        },
        {
            "name":"uuuuu",
            "value":"53.55"
        }
    ]
},
{
    "name":"test002",
    "cat":"test1",
    "loc":"y loc",
    "ings":[
        {
            "name":"trtrtr",
            "value":"11.0"
        },
        {
            "name":"wewew",
            "value":"19.0"
        }
    ],
    "nums":[
        {
            "name":"iuyt",
            "value":"122.05"
        },
        {
            "name":"oiui",
            "value":"15.5"
        }
    ]
}
生成的json文件(test1.json)应该如下所示

{
    "name":"test001",
    "cat":"test",
    "loc":"x loc",
    "ings":[
        {
            "name":"rrrrrr",
            "value":13.0
        },
        {
            "name":"hhhh",
            "value":18.0
        }
    ],
    "nums":[
        {
            "name":"kkkk",
            "value":82.05
        },
        {
            "name":"uuuuu",
            "value":53.55
        }
    ]
},
{
    "name":"test002",
    "cat":"test1",
    "loc":"y loc",
    "ings":[
        {
            "name":"trtrtr",
            "value":11.0
        },
        {
            "name":"wewew",
            "value":19.0
        }
    ],
    "nums":[
        {
            "name":"iuyt",
            "value":122.05
        },
        {
            "name":"oiui",
            "value":15.5
        }
    ]
}

您需要递归遍历数据,并将看起来像浮点的任何内容转换为浮点:

def fix_floats(data):
    if isinstance(data,list):
        iterator = enumerate(data)
    elif isinstance(data,dict):
        iterator = data.items()
    else:
        raise TypeError("can only traverse list or dict")

    for i,value in iterator:
        if isinstance(value,(list,dict)):
            fix_floats(value)
        elif isinstance(value,str):
            try:
                data[i] = float(value)
            except ValueError:
                pass
它应该做到这一点:

my_data = [
        {   "name" : "rrrrrr", 
            "value" : "13.0"  }, 
        {   "name" : "hhhh", 
            "value" : "18.0"  }, 
        ]

fix_floats(my_data)

>>> my_data
[{'name': 'rrrrrr', 'value': 13.0}, {'name': 'hhhh', 'value': 18.0}]

您可以为方法提供
object\u hook
,该方法允许您修改json中的任何对象(dicts):

import json

json_data = """
[{
    "name":"test001",
    "cat":"test",
    "loc":"x loc",
    "ings":[
        {
            "name":"rrrrrr",
            "value":"13.0"
        },
        {
            "name":"hhhh",
            "value":"18.0"
        }
    ],
    "nums":[
        {
            "name":"kkkk",
            "value":"82.05"
        },
        {
            "name":"uuuuu",
            "value":"53.55"
        }
    ]
},
{
    "name":"test002",
    "cat":"test1",
    "loc":"y loc",
    "ings":[
        {
            "name":"trtrtr",
            "value":"11.0"
        },
        {
            "name":"wewew",
            "value":"19.0"
        }
    ],
    "nums":[
        {
            "name":"iuyt",
            "value":"122.05"
        },
        {
            "name":"oiui",
            "value":"15.5"
        }
    ]
}]
"""

def as_float(obj):
    """Checks each dict passed to this function if it contains the key "value"
    Args:
        obj (dict): The object to decode

    Returns:
        dict: The new dictionary with changes if necessary
    """
    if "value" in obj:
        obj["value"] = float(obj["value"])
    return obj


if __name__ == '__main__':
    l = json.loads(json_data, object_hook=as_float)
    print (json.dumps(l, indent=4))
这将产生您想要的结果:

[
    {
        "loc": "x loc",
        "ings": [
            {
                "name": "rrrrrr",
                "value": 13.0
            },
            {
                "name": "hhhh",
                "value": 18.0
            }
        ],
        "name": "test001",
        "nums": [
            {
                "name": "kkkk",
                "value": 82.05
            },
            {
                "name": "uuuuu",
                "value": 53.55
            }
        ],
        "cat": "test"
    },
    {
        "loc": "y loc",
        "ings": [
            {
                "name": "trtrtr",
                "value": 11.0
            },
            {
                "name": "wewew",
                "value": 19.0
            }
        ],
        "name": "test002",
        "nums": [
            {
                "name": "iuyt",
                "value": 122.05
            },
            {
                "name": "oiui",
                "value": 15.5
            }
        ],
        "cat": "test1"
    }
]
改为写入文件:

with open("out.json", "w+") as out:
    json.dump(l, out, indent=4)

两者都是相同的文件。你想完成什么。你想得到彩车。保存到文件时它必须做什么?