简体   繁体   中英

Complex JSON object from CSV String in Python

I want the below JSON output after parsing csv string in Python to feed API:

{
   "_records":[
      {
         "_fields":{
            "Account":"DSP2",
            "Code":"11"
         }
      },
      {
         "_fields":{
            "Account":"DSP1",
            "Code":"11"
         }
      }
   ]
}

Since I am new to python after some research I was able to write the below code, which is working, but I am getting some additional junk characters in the final output.

Output:

{'records': [{'{"fields": {"Account": "T671", "Code": "A7710"}}'}, 
enter code here
"T672", "Code": "A7799"}}'}]}

can someone help on how to get rid of extra {' and '}?

Code -

data = {'records': []}

data1 = {}

line_var = input_var_1.splitlines()
for line in line_var:
    records = line.split(',')
    data1.update({'fields': {'Account': records[0].strip(),'Code': records[1].strip()}})
    data2 = json.dumps(data1)
data["records"].append({data2})

the additional {' is there because you dump the inner dictionary to a string and insert it into a set which you then put in the list.

Leave the data2 = json.dumps(data1) out and just insert data1 in your data["records"] . You'll get a proper list of dictionaries that you can use further

Only dump the dictionary if you need it's text-representation for writing it to a file etc.

You also don't need to initialize the data1 dictionary, just assign a new one in every loop and write it to the list. It will overwrite the reference by default

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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