熊猫字典到json追加到文件

时间:2019-01-10 01:15:54

标签: python json pandas

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

每本字典看起来像这样:

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对象不是逗号分隔的。当我尝试用熊猫加载它时,出现trailing Data ValueError

您可以看到它不是一个大数组,其中包含一堆json对象,它只是一堆非逗号分隔的json对象

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

谢谢你

2 个答案:

答案 0 :(得分:1)

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

答案 1 :(得分:0)

我建议您阅读文件,附加新数据,然后再写回。然后可以将其正确加载到大熊猫中。

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

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

欢呼

相关问题