skip to Main Content

I have a csv like this:

key spanish
no no
yes is
why porque

I want to make it into a json like this:

{
   "no": "no",
   "yes": "si",
   "why": "porque"
}

All the examples I have found online create JSON’s kind of like this:

{
    "no": {
        "key": "no",
        "Spanish": "no"
    }
}

I would like to write a python script that will create the simple key/value pairs in a json file.

2

Answers


  1. import csv
    import json
    
    myDict = {}
    with open('path/to/csv') as iFile:
     myCSV = csv.reader(iFile)
     for line in myCSV:
       k,v = line
       myDict[k] = v
    
    myJSON = json.dumps(myDict)
    
    Login or Signup to reply.
  2. Load you csv to dataframe, then use this:

    df.set_index('key')['spanish'].to_json('path/to/jsonfile.json')

    Neatly save the dataframe in json format.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search