回答此问题可获得 20 贡献值,回答如果被采纳可获得 50 分。
<p>我尝试从python字典数据类型生成JSON文件。你知道吗</p>
<p>在我将其转储为Json格式之前,下面是本期所涉及的python代码片段:</p>
<pre><code>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])
</code></pre>
<h2>航向</h2>
<p>我这样做是为了初始化字典索引,然后我可以在for循环中添加更多数据,如下所示:</p>
<pre><code>channelSeg["ch"] = None
channelSeg["chdata"] = []
</code></pre>
<p>但我真正想做的是不给他们分配任何数据</p>
<pre><code>channelSeg["ch"]
channelSeg["chdata"]
</code></pre>
<p>但是python不喜欢我这么做。你知道吗</p>
<p>所以在转储操作之后,我得到了重复的Json数据,就像这样(它的一部分)</p>
<pre><code>"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"
},
</code></pre>
<p>我总是有多余的:</p>
<pre><code> {
"ch": null,
"chdata": []
}
</code></pre>
<p>这使得这个JSON数据包不够健康,有没有办法删除这段冗余数据?你知道吗</p>
<p>非常感谢你的建议</p>
<p>=============v2==============</p>
<p>在我考虑了Edward的答案之后,我发现我只能用channelSeg[“ch”]=None来解决它,但我不知道如何处理另一个冗余列表,这是因为我没有发布足够的代码,所以我在这里通过了更完整的代码,仍然在寻找解决方案。。
修改后我的代码:</p>
<pre><code> 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
</code></pre>
<p>结果是这样的</p>
<pre><code> {
"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"
},
</code></pre>
<p>哪个</p>
<pre><code> {
"chdata": []
}
</code></pre>
<p>还在吗</p>