简体   繁体   English

python:追加到数据使用json.dumps

[英]python : append to data use json.dumps

I am trying to create JSON file. 我正在尝试创建JSON文件。 using json.dumps and success printing. 使用json.dumps并成功打印。 I have a question. 我有个问题。

The format I wanted was 我想要的格式是

channel_info = OrderedDict()
table = OrderedDict()
table2 = OrderedDict()

channel_info["KIND1"] = pkind[2].text
table[ptime[10].text] = pnk[11].text
table[ptime[11].text] = pnk[12].text
channel_info["TABLE1"] = table

channel_info["KIND2"] = pkind[2].text
table2[ptime[10].text] = pnk[11].text
table2[ptime[11].text] = pnk[12].text
channel_info["TABLE2"] = table2

result: 结果:

{
"KIND1": "xxxx",
"TABLE1": {
    "09:10": "aaaa",
    "10:10": "bbbb"
},
"KIND2": "yyyy",
"TABLE2": {
    "09:10": "cccc",
    "10:10": "dddd"
}

} }

How to output the same format using a while loop? 如何使用while循环输出相同格式? The names of the JSON objects? JSON对象的名称? KIND1, TABLE1, KIND2, TABLE2 and so on ... I wonder how you can change these names dynamically using a while loop. KIND1,TABLE1,KIND2,TABLE2等……我想知道如何使用while循环动态更改这些名称。 thank you. 谢谢。

You could do something like this (assuming table dictionary is static over each loop, as it seems in the example you give): 您可以执行以下操作(假设table字典在每个循环中都是静态的,如您所给出的示例所示):

channel_info = dict()
# n_tables is the number of iterations you need
for i in range(n_tables):
    table = dict()
    channel_info["KIND%s" % (i+1)] = pkind[1].text
    table[ptime[10].text] = pnk[11].text
    table[ptime[11].text] = pnk[12].text
    channel_info["TABLE%s" % (i+1)] = table

You don't need the table name dynamically since you assign it to a dictionary key. 由于将表名称分配给字典键,因此不需要动态使用表名称。

Basically, if I understood your question right: 基本上,如果我理解您的问题是正确的:

...
i=0
no_of_tables = 4 
while i<=no_of_tables:
  table_counter = i+1
  table_counter = str(table_counter)
  kind = 'KIND' + table_counter
  table = 'TABLE' + table_counter
  channel_info[kind] = pkind[2].text
  table[ptime[10].text] = pnk[11].text
  table[ptime[11].text] = pnk[12].text
  channel_info[table] = table

Note: I know it can be optimized, but for the sake of simplicity I left it as is. 注意:我知道可以对其进行优化,但是为了简单起见,我将其保留为原样。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM