2

I have sample csv data that looks like this:

id,hex1,hex2,hex3,hex4,hex5
388,#442c1c,#927450,#664c31,#22110c,
387,#6a442f,#826349,,,
1733,#4d432e,#75623f,,,
1728,#393e46,#5f4433,#ad7a52,#362c28,#a76042

I'd like to create JSON data from this csv that looks something like this:

{
  "images":[
    {
      "colors": [
        "#442c1c",
        "#2f4f4f",
        "#927450",
        "#696969",
        "#664c31",
        "#556b2f"
      ],
      "id": "388"
    }
  ]
}

Each row should take the first column (id) and create a dictionary/array (sorry, not sure of the correct terminology) containing the hex values within that row. Python is the langauge I'm most familiar with so I'd prefer to use that to create my JSON.

Can anyone suggest some starting points?

Thank you in advance.

0

1 Answer 1

3

You can use the following that basically is a list comprehension:

import csv

with open('file.csv', mode='r') as csv_file:
    reader = csv.DictReader(csv_file)
    next(reader, None)  # skip the header
    # id,hex1,hex2,hex3,hex4,hex5
    images = [{'colors': [row[f'hex{n}'] for n in range(1, 6) if row[f'hex{n}'] != ''], 'id': row["id"]} for row in reader]

d = {'images': images}

d will contain the dictionary you want:

{'images': [{'colors': ['#6a442f', '#826349'], 'id': '387'},
            {'colors': ['#4d432e', '#75623f'], 'id': '1733'},
            {'colors': ['#393e46', '#5f4433', '#ad7a52', '#362c28', '#a76042'],
             'id': '1728'}]}
Sign up to request clarification or add additional context in comments.

Comments

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.