I'm trying to transform a JSON file to a XLS file, but it returns me an error called:
-> name = record['name'] TypeError: byte indices must be integers or slices, not str
I've already tried do that thing with JS but I'm completely lost, I think Python Will be more easy to understand all of this
import os
import json
import win32com.client as win32 # pip install pywin32
import requests
"""
Step 1.1 Read the JSON file
"""
json_data = requests.get("https://restcountries.com/v3.1/all")
print(json_data.content)
"""
Step 1.2 Examing the data and flatten the records into a 2D layout
"""
rows = []
for record in json_data:
name = record['name']
"""
Step 2. Inserting Records to an Excel Spreadsheet
"""
ExcelApp = win32.Dispatch('Excel.Application')
ExcelApp.Visible = True
wb = ExcelApp.Workbooks.Add()
ws = wb.Worksheets(1)
header_labels = ('name')
# insert header labels
for indx, val in enumerate(header_labels):
ws.Cells(1, indx + 1).Value = val
# insert Records
row_tracker = 2
column_size = len(header_labels)
for row in rows:
ws.Range(
ws.Cells(row_tracker, 1),
ws.Cells(row_tracker, column_size)
).value = row
row_tracker += 1
wb.SaveAs(os.path.join(os.getcwd(), 'Json output.xlsx'), 51)
wb.Close()
ExcelApp.Quit()
ExcelApp = None
print()(andprint(type(...)),print(len(...)), etc.) to see which part of code is executed and what you really have in variables. It is called"print debuging"and it helps to see what code is really doing.json_data.json()orjson.loads(json_data.content)to get it as dictionary becausejson_data.contenthas it as bytesrowsbecause you forgotrow.append(name)insidefor-loop