Search code examples
pythonjsondictionarypyodbcdefaultdict

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


I'm building json format and the expected is as below:

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

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

If we have more than one account for customer:

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

After building the dictionary with required attributes for acct1, my code towards end is (and have question if I should be using collections module):

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)

But the actual json format comes out as:

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

Solution

  • Your print statement likely answers your question. Is it a list?

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

    I suspect you meant to do acctlist.append(results)