1

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
      }
    }   
}
more09
  • 57
  • 1
  • 7

1 Answers1

1

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)

Cireo
  • 4,197
  • 1
  • 19
  • 24
  • Ops you are correct @Cireo. It is a list and acctlist.append(results) is what I intend to do. So if I have mutiple accts for customer, in that case I would initialize the results = {} , outside the loop (which would run for each acct) ? – more09 Sep 08 '19 at 15:31
  • Yes, you would need to have this code properly isolated from the outer loop if you were re-using it for multiple accounts – Cireo Sep 09 '19 at 23:00