繁体   English   中英

pandas 字典到 json 追加到文件

[英]pandas dictionary to json append to file

我正在尝试将每个包含 3 个项目的字典写入一个 json 文件,我最终将与 Pandas 一起使用。

每个字典看起来像这样:

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

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

with open('jsonfile.json', 'a') as json_file:
    json_file.write(json.dumps(xyz_dictionary, indent=4))

我的情况是不断创建新的“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 ValueError

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

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

感谢你

编辑:我建议你创建一个 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

outfile = "Pathforfile.csv"
list = []
xyz_dictionary = {'x': 1, 'y': 2, 'z':3}
list.append(xyz_dictionary)
.... #append all xyz values
data = {'xyz' : list}
json_data = json.dumps(data) # save the data in Json format
json.dump(data, outfile) # or save it directly to a file 

读取文件

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

我建议您阅读该文件,附加新数据,然后将其写回。 然后你可以正确地将它加载到 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

这是未经测试的,因为我不在我的工作站,但希望它能够理解这个概念。 让我知道是否有任何错误!

干杯

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM