pandas dictionary to json append to fi

2024-04-26 21:38:50 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在尝试将每个包含3个条目的字典编写到一个json文件中,最终我将在pandas中使用它。在

每本字典都是这样的:

xyz_dictionary = {'x': 1, 'y': 2, 'z':3}

我正在执行以下操作,使其成为一个字符串,然后将其添加到.json文件中:

^{pr2}$

我的情况是,新的'xyz'字典不断被创建,所以我必须将每个字典转换成json格式,然后将其附加到json文件中。问题是,在我完成后,我的json文件会变成这样:

 {
    "x": -0.03564453125,
    "y": -0.00830078125,
    "z": 1.0244140625
}{
    "x": -0.0361328125,
    "y": -0.0087890625,
    "z": 1.0244140625
}{
    "x": -0.0390625,
    "y": -0.0087890625,
    "z": 1.025390625
}{
    "x": -0.03662109375,
    "y": -0.0087890625,
    "z": 1.0263671875
}

其中json对象没有逗号分隔。当我尝试用pandas加载这个时,我得到一个trailing Data值错误

正如你所看到的,它不是一个大数组,里面有一堆json对象,它只是一堆非逗号分隔的json对象

总而言之,问题是“如何创建逗号分隔的json对象并将它们写入一个.json文件,该文件是所有对象的编译?”在

谢谢你


Tags: 文件对象字符串目的jsonpandasdatadictionary
2条回答

我建议你读这个文件,附加新的数据然后写回去。然后就可以正确地将其加载到pandas中。在

import json, os
import pandas as pd

filepath = 'jsonfile.json'

class get_file:
    def __init__(self, path):
        self.path = path or filename
    def __enter__(self):
        #see if file exists and create if not
        data = {'xyz_data':[]}
        if not os.path.isfile(path):
            file = open(path, 'rw')
            json.dump(data, file)
        else:
            #This is just to ensure that the file is valid json
            #if not it replaces the old datafile with a blank json file
            #This is hacky and you will lose all old data!
            file = open(path, 'rw') as file:
            try:
                data = json.load(file)
            except ValueError:
                json.dump(data, file)

        #this line can be deleted, just shows the data after opening
        print(data)
        self.file = file
        return file

    def __exit__(self):
        self.file.close()

def append_data(data, path: str=None):
    """Appends data to the file at the given path, defaults to filepath"""
    path = path or filepath
    with get_data(path) as json_file:
        d = json.load(json_file)
        d = d['xyz_data']
        if isinstance(d, list):
            d.extend(data)
        elif isinstance(d, dict):
            d.append(data)
        else:
            raise TypeError("Must be list or dict")
        json.dump(d, json_file)

def get_dataframe(path):
    path = path or filepath
    with get_data(path) as json_file:
        data = json.load(json_file)
        df = pd.DataFrame(data['xyz_data'])
    return df

这是未经测试的,因为我不在我的工作站上,但希望它能让人理解这个概念。 如果有错误请告诉我!在

干杯

编辑:我建议您创建一个json对象数组

import json

{ 'xyz_data': 
[{
    "x": -0.03564453125,
    "y": -0.00830078125,
    "z": 1.0244140625
},
{
    "x": -0.03564453125,
    "y": -0.00830078125,
    "z": 1.0244140625
}, ...
]}

使用append添加到dic

^{pr2}$

读取文件

json_data=open(file_directory).read()
data = json.loads(json_data)

相关问题 更多 >