Proteeti Prova
Proteeti Prova

Reputation: 1169

CSV to nested JSON Python

I have a csv file which only has one column consisting of 200 rows. I want to use each row count as "priority" and each row value as "name", obtaining the following json format:

[{ "model" : "mymodel",
   "pk" : ROW_ID,
   "fields":{
      "name" : ROW_VALUE,
      "priority" : ROW_ID
},
{ "model" : "mymodel",
   "pk" : ROW_ID,
   "fields":{
      "name" : ROW_VALUE,
      "priority" : ROW_ID
}]

I know that I have to use csv and json, but quite confused about the nested json format. Any help on this?

Upvotes: 0

Views: 160

Answers (1)

Mark
Mark

Reputation: 92461

You just need to open the file and loop through the lines. You can use enumerate() to get the value of the line number (starting at zero). Build an array of dictionaries and the pass it to json.dumps to make a JSON string:

import json

with open(filePath) as f:
    next(f) #skip the header
    l = []
    for line, value in enumerate(f):
        l.append({
            "model" : "mymodel",
            "pk": line,
            "fields": {
                "name": value.strip(),
                "priority": line
            }
        })
print(json.dumps(l))
# or for indented output like below:
# json.dumps(l, indent=2) 

This will print:

[
  {
    "model": "mymodel",
    "pk": 1,
    "fields": {
      "name": "Afghanistan",
      "priority": 0
    }
  },
  {
    "model": "mymodel",
    "pk": 2,
    "fields": {
      "name": "Albania",
      "priority": 1
    }
  },
  ...
]

Upvotes: 1

Related Questions