Search code examples
pythonjsoncsvdictionaryapi-design

CSV to JSON with Specific format


I Have csv file with this data and using python i would like to convert in json Format.

I would like to convert in this format Json Format.Can you tell me the which library i should use or any suggestion for sudo code. I am able to convert in standard json which has key value pair but i don't know how to convert below Json Format.

"T-shirt","Long-tshirt",18
"T-shirt","short-tshirt"19
"T-shirt","half-tshirt",20
"top","very-nice",45
"top","not-nice",56

{
"T-shirts":[
  {
  "name":"Long-tshirt",
  "size":"18"
  },
  {
  "name":"short-tshirt",
  "size":"19"
  },
  {
  "name":"half-tshirt",
  "size":"20"
  },
  ],
"top":[
  {
  "name":"very-nice"
  "size":45
  },
  {
  "name":"not-nice"
  "size":45
  },
  ]
}


Solution

  • In this code, I put your CSV into test.csv file: (as a heads up, the provided code was missing a comma before the 19).

    "T-shirt","Long-tshirt",18
    "T-shirt","short-tshirt",19
    "T-shirt","half-tshirt",20
    "top","very-nice",45
    "top","not-nice",56
    

    Then, using the built-in csv and json modules you can iterate over each row and add them to a dictionary. I used a defaultdict to save time, and write out that data to a json file.

    import csv, json
    from collections import defaultdict
    
    my_data = defaultdict(list)
    
    with open("test.csv") as csv_file:
        reader = csv.reader(csv_file)
        for row in reader:
            if row: # To ignore blank lines
                my_data[row[0]].append({"name": row[1], "size": row[2]})
    
    
    with open("out.json", "w") as out_file:
        json.dump(my_data, out_file, indent=2)
    

    Generated out file:

    {
      "T-shirt": [
        {
          "name": "Long-tshirt",
          "size": "18"
        },
        {
          "name": "short-tshirt",
          "size": "19"
        },
        {
          "name": "half-tshirt",
          "size": "20"
        }
      ],
      "top": [
        {
          "name": "very-nice",
          "size": "45"
        },
        {
          "name": "not-nice",
          "size": "56"
        }
      ]
    }