【发布时间】:2019-11-04 03:16:42
【问题描述】:
我有一个添加到列表的 Python 脚本:
column = defaultdict(list)
[...]
for line in out.splitlines():
column[i + 1].append({"row": str(line)})
[...]
f = open(save_dir + 'table_data.json', "w+")
f.write(json.dumps(column))
f.close()
这最终会生成一个 JSON 文件,字符串如下:
{ "1":[
{
"row":"Product/Descriptian"
}
],
"2":[
{
"row":"Qty/unit"
},
{
"row":"Text"
}
],
"3":[
{
"row":""
}
]}
如您所见,array["2"] 有两个值。我正在尝试使所有数组的长度相同。所以array["1"] 和array["3"] 最终也会有两个值。
所以为了做到这一点,我想我必须先找到最长的数组:
longest_array = (max(map(len, column.values())))
这应该返回2。现在我想将一个空的{"row":""} 附加到其他数组,使其长度相同:
final = ([v + ["{'row'}: ''"] * (longest_array - len(v)) for v in column.values()])
哪些输出低于 JSON 字符串:
[
[
{
"row":"Product/Descriptian"
},
{
"row":""
}
],
[
{
"row":"Qty/unit"
},
{
"row":"Text"
}
],
[
{
"row":""
},
{
"row":""
}
]
]
这似乎部分起作用。但是,我在新创建的 JSON 字符串中发现了两个错误:
似乎在第一个数组周围添加了另一个数组。 JSON 字符串现在以
[ [ { 开头
它删除了“父”数组
"1", "2" and "3"
【问题讨论】:
-
你有没有试过在一开始就改变字典,在转储之前?纠正 JSON 字符串似乎更容易
-
不太确定我该怎么做,因为列表是动态创建的?事先不知道什么数组最长
-
当然在转储前你也可以直接调用:
longest_array = (max(map(len, column.values())))然后相应地编辑字典 -
我在写入文件之前调用
final = ...