[Python] Coverting CSV file to a JSON

Discussão em 'Python' iniciado por Stack, Junho 20, 2025.

  1. Stack

    Stack Membro Participativo

    I'm wanting to convert data in a CSV file to a nested JSON file, I want the data too look like this

    "parent_id": 114073, "title": "t shirt", "description": "it just a white tee", "link": "https://www.weselltshirt.com/whitetee" "price": "69.95",: "varinats":[ { "variant_id": 114083, "sku": "COL-WD-DIA-6" "Size": "Small"

    },
    {
    "variant_id": 114082,
    "sku": "COL-WD-DIA-8"
    "Size": "Medium"
    },


    Sample data

    import itertools, csv data = [[int(b) if b.isdigit() else b for b in i] for i in csv.reader(open('bowlerstest.csv'))][1:] headers = ['parent_id', 'variants', 'title', 'variant_id', 'description', 'price', 'link', 'Size', 'sku'] def create_structure(d, headers = headers): c = [[a, list(b)] for a, b in itertools.groupby(sorted(d, key=lambda x:x[0]), key=lambda x:x[0])] return [{headers[0]:a, headers[1]:create_structure([i for _, *i in b], headers = headers[4:]) if len(headers[8:]) > 8 else [dict(zip(headers[2:], i)) for _, *i in b]} for a, b, in c]

    import json print(json.dumps(create_structure(data), indent = 4))

    I pulled this from a post I saw prevouisly and tried using it, I've play around and modified it to inlcude the different headers before the create_stucture, but it does'nt product the results I'm looking for. What do I need to add or modifiy to get this to work? Do i need the change the list order and header order in the file?

    Continue reading...

Compartilhe esta Página