我需要动态构建以下 JSON 结构。json = { "mainkey":"val1", "key2":[ {"keya":"val1rec1","keyb":"val2rec1","keyc":"val3rec1"}, {"keya":"val1rec2","keyb":"val2rec2","keyc":"val3rec2"}, {"keya":"val1rec3","keyb":"val2rec3","keyc":"val3rec3"}, {"keya":"val1rec4","keyb":"val2rec4","keyc":"val3rec4"}, {"keya":"val1rec5","keyb":"val2rec5","keyc":"val3rec5"} ] }只有 "{"keya":"val1rec1","keyb":"val2rec1","keyc":"val3rec1"}," 行 "迭代" - 即从 CSV 文件中读取值,然后填充/创建行基于 CSV 文件中的内容。所以我的伪代码看起来像这样:#create dictpath = 'somewhere\on\my\disk\file.csv'json_file = {}json_file['mainkey'] = "val1" #read from CSV filedf1 = pd.read_csv(path, header=None) #iterate through csvfor row,s in df1.iterrows(): number = df1.loc[row,0] #I'm reading keyb and keyc values from CSV as well, but for brevity my substitution below is not showing that.... json_file['key2'] = "'keya':'"+str(number)+"','keyb':'whatever','keyc':'whatever'"print (json_file)它显然无法产生我在上面寻找的东西 - 因此我在这里发帖寻求帮助。
2 回答
宝慕林4294392
TA贡献2021条经验 获得超8个赞
您正在覆盖key2值,而您应该将它们附加到列表中:
json_file['key2'] = []
for row,s in df1.iterrows():
number = df1.loc[row,0]
json_file['key2'].append({'keya': str(number), 'keyb': 'whatever', 'keyc': 'whatever'})
print (json_file)
添加回答
举报
0/150
提交
取消