0

I trying to parse names from a CSV and turn them into a JS Array, this my first attempt at using python and I'm having trouble getting the right structure for the JSON file. My code is below with the current and desired output, any pointers would be greatly appreciated.

import csv, json

csvPath = "forbes_pub_top_2000.csv"
jsonPath = "pub.json"

# Read CSV, filter Names, add to data
data = {}
with open(csvPath, 'r') as csv_file:
    csv_reader = csv.reader(csv_file)

    next(csv_reader)

    for line in csv_reader:
        company = line[2]
        data[company] = line[2]

# Add data to root node
root = {}
root["names"] = data

# Write data to JSON file
with open(jsonPath, 'w') as json_file:
        json_file.write(json.dumps(root, indent=4))

Current output:

{
    "names": {
        "ICBC": "ICBC",
        "China Construction Bank": "China Construction Bank",
        "Berkshire Hathaway": "Berkshire Hathaway",
        "JPMorgan Chase": "JPMorgan Chase",
        "Wells Fargo": "Wells Fargo",
        "Agricultural Bank of China": "Agricultural Bank of China",
        "Bank of America": "Bank of America",
        "Bank of China": "Bank of China",

    ...
}

Desired Output:

{
    "names": ["ICBC", "China Construction Bank", "Berkshire Hathaway", "JPMorgan Chase", "Wells Fargo", "Agricultural Bank of China", "Bank of America", "Bank of China", ... ]
}

1 Answer 1

1

Instead of this:

for line in csv_reader:
    company = line[2]
    data[company] = line[2]

do this:

for line in csv_reader:
    data.append(line[2])

You will also need to make data a list, not a dict:

data = []
Sign up to request clarification or add additional context in comments.

1 Comment

That works great! Thank you for taking the time to reply.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.