首页 > 解决方案 > 用数据框替换 json 文件中的数据

问题描述

我有以下格式的 json 文件

"rawDataBody":
    {
        "data": [
        {
            "name": "Test",
            "unit": "",
            "format": "integer",
            "key": "Test"
           }
        ],
        "dataBlock": [
        [7, 1730569828, 3490, 1608636960, 30.62, 1003.82, 44.14, 683806.38, 2, 1, 0, 0],
        [0, 1730563432, 3545, 1608636960, 29.89, 1003.52, 39.25, 557582.38, 2, 1, 0, 0],
        [1, 1730579048, 3571, 1608636960, 29.79, 1003.45, 41.07, 494566.53, 2, 1, 0, 0],
        [2, 1730568292, 3595, 1608636960, 29.62, 1003.40, 42.72, 546424.75, 2, 1, 0, 0],

我想用我的数据框替换 dataBlock 中的数据并将整个提取到 json 文件中

5.0,1730566755.0,22.11,1608636969.0,33.42,1003.5,39.78,60591.71,9.0,1.0,0.0,0.0
6.0,1730551139.0,22.14,1608636969.0,33.27,1003.64,38.77,77906.27,9.0,1.0,0.0,0.0
6.0,1730551139.0,22.14,1608636969.0,33.27,1003.64,38.77,77906.27,9.0,1.0,0.0,0.0
5.0,1730566755.0,42.11,1608636969.0,33.42,1003.5,39.78,60591.71,9.0,1.0,0.0,0.0

我试过的代码是。我不知道为什么这不起作用。有人可以帮我吗

with open('data.txt', 'r') as file:
    jsonData = json.load(file)
    dfFinalResult = dfFinalResult.values.tolist()
    for item in jsonData['rawDataBody']['dataBlock']:
        item = dfFinalResult
    with open('newjsonfile.txt', 'w') as file:
        json.dump(jsonData, file)

标签: pythonpython-3.xpandas

解决方案


你似乎在说我的建议奏效了。

这是我认为你应该拥有的:

with open('data.txt', 'r') as file:
    jsonData = json.load(file)

dfFinalResult = dfFinalResult.values.tolist()
jsonData['rawDataBody']['dataBlock'] = dfFinalResult

with open('newjsonfile.txt', 'w') as file:
    json.dump(jsonData, file)

推荐阅读