构建 JSON 格式的问题。在 dict 和 collections 之间选择?

Issue with building JSON format. Choose between dict and collections?

我正在构建 json 格式,预期如下:

{   
 accounts:[   {
      "acctnum": "acct1",
      "key2":"value2"
      "key3": []
      "summary" : {
          //nested dict
      }
    }

   ]  //if we have 1 account for given customer     
}

如果我们有多个客户账户:

{   
 accounts:[   {
      "acctnum": "acct1",   // for acct1
      "key2":"value2"
      "key3": []
      "summary" : {
          //nested dict
      }
    },
    {
        "acctnum": "acct2",   //for acct2
        "key2":"value3"
        "key3": []
        "summary" : {
            //nested dict
        }
      }  
    ]       
}

在为 acct1 构建具有所需属性的字典后,我最后的代码是(并且有疑问我是否应该使用集合模块):

acctlist = []
acctlist = results  //results is dict for acct1 (with nested dict)
print(acctlist)
accounts  = {}
accounts["accounts"] = acctlist
j = json.dumps(accounts, indent=4)
print(j)

但实际的 json 格式为:

{   
 accounts: {
      "acctnum": "acct1",
      "key2":"value2"
      "key3": []
      "summary1" : {
          //nested dict
      }
    }   
}

您的打印语句可能会回答您的问题。是列表吗?

acctlist = []
acctlist = results  //results is dict for acct1 (with nested dict)
print(acctlist)

我怀疑你是故意的acctlist.append(results)