0

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?

2
  • 1
    In what sense is your file csv if it only has one column. Is it just a list of 200 values separated by line breaks? Commented Feb 3, 2020 at 3:45
  • It looks like this : imgur.com/GaZdgk4 @MarkMeyer Commented Feb 3, 2020 at 3:48

1 Answer 1

1

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
    }
  },
  ...
]
Sign up to request clarification or add additional context in comments.

1 Comment

Added print(json.dumps(l,indent=4)) with open('data.json', 'w') as outfile: json.dump(l, outfile, indent= 4) for prettifying the json and open it in a file.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.