我正在尝试将包含 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 对象不以逗号分隔。当我尝试用熊猫加载它时,我得到一个trailing Data
值错误
如您所见,它不是一个包含一堆 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
}, ...
]}
使用追加添加到 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)
我建议您读取文件,附加新数据,然后将其写回。然后你可以正确地将其加载到熊猫中。
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
这是未经测试的,因为我不在我的工作站,但希望它能传达这个概念。如果有任何错误,请告诉我!
干杯
新数据附加到与 Pandas 兼容的 json,你将面临这样一个事实,即没有像to_csv那样mode="a"
。但是,我们仍然可以轻松且节省内存地将数据帧附加到 JSON。只需在to_json
方法中使用orient='records', lines=True
即可。
with open(out_path, "a") as out:
newdf = pd.DataFrame(data)
newdf.to_json(out, orient='records', lines=True)
然后,您可以以相同的方式读取整个数据集。
newdf = pd.read_json(out_path, orient='records', lines=True)