我有一个需要转换为 json 字典的 python 列表列表。名单如下:
[
['[{"name":"david","level":"k","xaxis":[[]],"yaxis":[[]],', '"count":[[2011, 6], [2012, 0], [2013, 11]]},'],
['{"name":"marshall","level":"n","xaxis":[[]],"yaxis":[[]],',
'"count":[[2008, 130], [2009, 53], [2010, 10], [2011, 17], [2012, 0], [2013, 142]]}]']
]
我需要的是:
{
[
{
"name": "david",
"level": "k",
"xaxis": [[]],
"yaxis": [[]],
"count":[[2011, 6], [2012, 0], [2013, 11]]
},
{
"name": "diana",
"level": "k",
"xaxis": [[]],
"yaxis": [[]],
"count":[[2011, 6], [2012, 0], [2013, 11]]
}
]
}
所以基本上,它将是一个包含子列表的字典,每个子列表都有一个字典。如何用我所拥有的来实现?
更新:
因此,为了清楚起见,让我将其分解为几个步骤。我需要这样的数据结构(我正在转储到 .json 文件中):
[{
"name": "David",
"level": "s",
"xaxis": [
[]
],
"yaxis": [
[]
],
"count": [
[2008, 128],
[2009, 51],
[2010, 10],
[2011, 17],
[2012, 0],
[2013, 142]
]
}, {
"name": "Diana",
"level": "v",
"xaxis": [
[]
],
"yaxis": [
[]
],
"count": [
[2008, 11],
[2009, 0],
[2010, 1],
[2011, 2],
[2012, 0],
[2013, 6]
]
}]
所以我构建它的方式如下:
首先,我有两个列表-> 名称和计算:
names = ['David', 'Diana']
calculations = [[[2011, 6], [2012, 0], [2013, 11]], [[2008, 130], [2009, 53], [2010, 10], [2011, 17], [2012, 0], [2013, 142]]]
其中“计算”是列表列表的列表。
从这两个列表中,我创建了最初提到的结构,如下所示:
import random
from compiler.ast import flatten
names_final = []
calculations_final = []
completed = []
for a in names:
names_final.append('{"name":"'.encode('utf-8')+a.encode('utf-8')+'","level":"'.encode('utf-8')+random.choice('abcdefghijklmnopqrstuvwxyz').encode('utf-8')+'","xaxis":[[]],"yaxis":[[]],'.encode('utf-8'))
for b in calculations:
calculations_final.append('"count":'.encode('utf-8')+str(b).encode('utf-8')+'},'.encode('utf-8'))
for i,j in map(None, names_final, calculations_final):
completed.append(flatten([i,j]))
然后最后到完成的列表,我正在做以下修改以获得我需要的东西:
completed[0][0]='['+completed[0][0]
completed[-1][-1]= completed[-1][-1][:-1]
completed[-1][-1]=completed[-1][-1]+']'
这导致该问题最顶部提到的输出列表。我需要的是根据用户定义的查询将其转换为 json 对象,以便可以通过浏览器将其作为 json 对象查看。我希望这会澄清。你们有什么建议?