我尝试从python字典数据类型生成JSON文件。你知道吗
在我将其转储为Json格式之前,下面是本期所涉及的python代码片段:
channelSeg = {}
channelSeg["ch"] = None
channelSeg["chdata"] = []
for e in channelPkg:
print e
attr = e.split(':')
if attr[0] == "ch":
channel = attr[1].split(',')
channelSeg["ch"] = int(channel[0])
我这样做是为了初始化字典索引,然后我可以在for循环中添加更多数据,如下所示:
channelSeg["ch"] = None
channelSeg["chdata"] = []
但我真正想做的是不给他们分配任何数据
channelSeg["ch"]
channelSeg["chdata"]
但是python不喜欢我这么做。你知道吗
所以在转储操作之后,我得到了重复的Json数据,就像这样(它的一部分)
"datapkg": [
{
"dataseg": [
{
"ch": 0,
"chdata": [
{
"euler": {
"y": "-19.32",
"x": "93.84",
"z": "-134.14"
}
},
{
"areal": {
"y": "57",
"x": "-242",
"z": "-210"
}
}
]
},
{
"ch": 1,
"chdata": [
{
"areal": {
"y": "-63",
"x": "-30",
"z": "10"
}
}
]
},
{
"ch": null,
"chdata": []
}
],
"t": "174464",
"n": "9884"
},
我总是有多余的:
{
"ch": null,
"chdata": []
}
这使得这个JSON数据包不够健康,有没有办法删除这段冗余数据?你知道吗
非常感谢你的建议
=============v2==============
在我考虑了Edward的答案之后,我发现我只能用channelSeg[“ch”]=None来解决它,但我不知道如何处理另一个冗余列表,这是因为我没有发布足够的代码,所以我在这里通过了更完整的代码,仍然在寻找解决方案。。 修改后我的代码:
for elem in sensorPkg:
channelPkg = elem.split('&') # channelPkg contain each channel's reading
# each channel need a dictonary to store data
channelSeg = {}
# channelSeg["ch"] = None
channelSeg["chdata"] = []
for e in channelPkg:
attr = e.split(':')
if attr[0] == "ch":
new_channel = {
'ch': int((attr[1].split(','))[0])
#channelSeg["ch"] = int(channel[0])
}
channelSeg["chdata"].append(new_channel)
# store channel numbers
elif attr[0] == "euler":
# create euler package
numbers = attr[1].split(',')
eulerSeg = {}
d = {}
d["x"] = numbers[0]
d["y"] = numbers[1]
d["z"] = numbers[2]
eulerSeg["euler"] = d
# append to channel segement
channelSeg["chdata"].append(eulerSeg)
elif attr[0] == "areal": # real accelrometer readings
# create areal package
numbers = attr[1].split(',')
arealSeg = {}
d = {}
d["x"] = numbers[0]
d["y"] = numbers[1]
d["z"] = numbers[2]
arealSeg["areal"] = d
# append to channel segement
channelSeg["chdata"].append(arealSeg)
#and so on
结果是这样的
{
"dataseg": [
{
"chdata": [
{
"ch": 0
},
{
"euler": {
"y": "6.51",
"x": "73.16",
"z": "-133.69"
}
},
{
"areal": {
"y": "516",
"x": "-330",
"z": "-7"
}
}
]
},
{
"chdata": [
{
"ch": 1
},
{
"euler": {
"y": "24.86",
"x": "4.30",
"z": "-71.39"
}
},
{
"areal": {
"y": "120",
"x": "316",
"z": "273"
}
}
]
},
{
"chdata": [
{
"ch": 2
},
{
"euler": {
"y": "62.32",
"x": "-60.34",
"z": "-120.82"
}
},
{
"areal": {
"y": "440",
"x": "-611",
"z": "816"
}
}
]
},
{
"chdata": []
}
],
"t": "14275",
"n": "794"
},
哪个
{
"chdata": []
}
还在吗
在您使用的数据结构中,我注意到“dataseg”是通道列表。现在,在将每个通道添加到dataseg之前,不需要对其进行初始化。首先将dataseg初始化为空列表,然后在channelPkg中迭代条目时,可以使用从channelPkg读取的信息创建新的channel dict,并立即追加它们:
希望这有帮助我不知道你的问题确切的背景是什么,所以评论如果这不能解决你的问题。你知道吗
编辑
我认为你的问题是最后一个
channelPkg
是空的。因此,for e in channelPkg:
等价于for e in []
,因此,外循环的最后一次迭代只附加初始化值(在for e in channelPkg
内没有任何内容执行)。你知道吗尝试添加两行来测试
sensorPkg
是否有ch
属性(我假设所有有效的sensorPkg
都有ch
属性):尝试使用条件词典:
相关问题 更多 >
编程相关推荐