Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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 :

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

{'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})

>Solution :

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

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading