我试图从JSON文件中提取一些数据,这些文件都具有相同的结构,然后将所选数据写入一个新的JSON文件。我的目标是创建一个新的JSON文件,该文件或多或少是我文件夹中每个JSON文件的列表,其中包含以下数据: 文件名,triggerdata,速度{imgVel,trigVel},坐标
在我的程序的下一步中,我需要这个新的splitTest1来分析不同文件的数据
我有以下代码:
base_dir = 'mypath'
def createJsonFile() :
splitTest1 = {}
splitTest1['20mm PSL'] = []
for file in os.listdir(base_dir):
# If file is a json, construct it's full path and open it, append all json data to list
if 'json' in file:
json_path = os.path.join(base_dir, file)
json_data = pd.read_json(json_path, lines=True)
if splitTest1[file]['20mm PSL'] == to_find:
splitTest1['20mm PSL'].append({
'filename': os.path.basename(base_dir),
'triggerdata': ['rawData']['adcDump']['0B'],
'velocity': {
'imgVel': ['computedData']['particleProperties']['imgVelocity'],
'trigVel': ['computedData']['img0Properties']['coordinates']},
'coordinates': ['computedData']['img1Properties']['coordinates']})
print(len(splitTest1))
运行代码时,出现以下错误:
'triggerdata': ['rawData']['adcDump']['0B'], TypeError: list indices must be integers or slices, not str
代码有什么问题?我该如何解决这个问题
这是我以前的代码,我是如何访问该数据而不将其保存在另一个JSON文件中的:
with open('myJsonFile.json') as f0:
d0 = json.load(f0)
y00B = d0['rawData']['adcDump']['0B']
x = np.arange(0, (2048 * 0.004), 0.004) # in ms, 2048 Samples, 4us
def getData():
return y00B, x
def getVel():
imgV = d0['computedData']['particleProperties']['imgVelocity']
trigV = d0['computedData']['trigger']['trigVelocity']
return imgV, trigV
基本上,我试图将最后一个代码片段放入一个循环中,该循环读取我文件夹中的所有JSON文件,并创建一个新的JSON文件,其中包含这些文件的名称和一些其他选择的数据(如['rawData']['adcDump']['0B']等)
希望这有助于更好地理解我的问题
问题在于这一行
'imgVel': ['computedData']['particleProperties']['imgVelocity'],
之后的两个。这里发生的事情是,您正在创建一个以字符串“computedData”作为唯一元素的列表。然后试图找到“particleproperty”索引,这毫无意义。只能使用整数为列表编制索引。我真的不能给你一个“解决方案”,但是如果你想把
imgVel
仅仅作为那些字符串的列表,那么你可以这样做'imgVel': ['computedData', 'particularProperties', 'imgVelocity']
我假设您要做的是从几个json文件中获取一些数据,并将它们编译成一个列表,然后将其写入一个新的json文件
为了从当前json文件中获取数据,需要在索引前面添加一个“引用”(否则代码不知道该数据来自何处)。像这样:
因此,基本上您需要做的是在索引前面添加“json_数据”
我还建议您将变量“json_path”而不是“base_dir”写入“filename”字段
我在Mattu475的帖子的帮助下找到了解决方案
我不得不在索引前添加引用,并用以下代码更改如何打开文件夹中的文件
而不是pd.read_json(…)
以下是完整的代码:
有几行(注释掉的那几行)还不能100%正常工作,但其余的行可以正常工作
谢谢你的帮助
相关问题 更多 >
编程相关推荐