1

I'm new to Python and I need some help to parse and insert this specific value from JSON file to CSV file.

Here's a snip of my JSON file

{
    "data": [
        {
            "id": 5555,
            "name": "Dodge Ram",
            "custom_data_field": [
                {
                    "id": 1,
                    "label": "black",
                    "value": 2018
                },
                {
                    "id": 2,
                    "label": "yellow",
                    "value": 2017
                },
                {
                    "id": 3,
                    "label": null,
                    "value": null
                },
                {
                    "id": 4,
                    "label": null,
                    "value": null
                }
            ],
            "access_groups": []
        }
    ]

I want to get CSV output like this

VehicleId |    name   | custom_id_1 | custom_label_1 | custom_id_2 | custom_label_2 
5555      | Dodge RAM | 1           | black          | 2           | yellow

Here's my Python code:

filename = "output.csv"
api_response = response.json()
with open(filename, "w") as file:
    csv_file = csv.writer(file, lineterminator='\n')
    
    csv_file.writerow(["VehicleId", "Name", "custom_id_1", "custom_label_1", "custom_id_2", "custom_label_2"])
        
    for item in api_response["data"]:
       for key in item["custom_id_field"]
           csv_file.writerow([item['id'], item['name'], key['id'], key['label'], key['id'], key['label'])

It does not give me the exact output like I wanted.

VehicleId |    name   | custom_id_1 | custom_label_1 | custom_id_2 | custom_label_2 
5555      | Dodge RAM | 1           | black          |             | 
5555      | Dodge RAM | 2           | yellow         |             |

Any help is appreciated. Thank you!

  • Does this answer your question? [How can I convert JSON to CSV?](https://stackoverflow.com/questions/1871524/how-can-i-convert-json-to-csv) – Charles Dupont May 12 '21 at 19:28

0 Answers0