Skip to content Skip to sidebar Skip to footer

How To Convert Specific Csv Format To Json Using Python

I have downloaded a CSV file from Google Trends which presents data in this format: Top cities for golden globes City,golden globes New York (United States),100 Los Angeles (United

Solution 1:

Your input format is so expectable that I would do it by hand, without a CSV library.

import json
from collections import defaultdict

fh = open("yourfile.csv")
result = defaultdict(dict) #dictionary holding the data
current_key = ""#current category
ignore_next = False#flag to skip headerfor line in fh:
    line = line.strip() #throw away newlineif line == "": #line is empty
        current_key = ""continueif current_key == "": #current_key is empty
        current_key = line #so the current line is the header for the following data
        ignore_next = Truecontinueif ignore_next: #we're in a line that can be ignored
        ignore_next = Falsecontinue
    (a,b) = line.split(",")
    result[current_key][a] = b
fh.close()

#pretty-print dataprint json.dumps(result, sort_keys=True, indent=4)

Solution 2:

I'd try something like...:

row = []
dd = {}
withopen('the.csv') as f:
    r = csv.reader(f)
    whileTrue:
        if row:  # normal case, non-empty row
            d[row[0]] = row[1]
            row = next(r, None)
            if row isNone: breakelse:  # row is empty at start and after blank line
            category = next(f, None)
            if category isNone: break
            category = category.strip()
            next(r)  # skip headers row
            d = dd[category] = {}
            row = next(r, None)
            if row isNone: break

Now, dd should be the dict-of-dicts you want, and you can json.dump it as you wish.

Post a Comment for "How To Convert Specific Csv Format To Json Using Python"