Skip to content

Instantly share code, notes, and snippets.

@mahimairaja
Created June 8, 2023 12:11
Show Gist options
  • Save mahimairaja/48f8d8f05f72cc208d6c618ec2319b90 to your computer and use it in GitHub Desktop.
Save mahimairaja/48f8d8f05f72cc208d6c618ec2319b90 to your computer and use it in GitHub Desktop.
To write a excel using the data from json.
import pandas as pd
import json
def readJson(filename,) -> dict:
"""
Reads a json file and returns a dictionary
"""
file = open(filename, 'r')
data = file.read()
file.close()
jsonData = json.loads(data)
return jsonData
def getDataframe(jsonData, metricName) -> pd.DataFrame:
"""
Returns a dataframe with the following columns:
"""
df = pd.DataFrame(jsonData[metricName])
df["metric1"] = jsonData["metric1"]
df["metric2"] = jsonData["metric2"]
df = df[["metric1", "metric2", "x", "y"]]
return df
def writeExcel(dataframe, filepath) -> None:
"""
Writes the dataframe to an excel file
"""
dataframe.to_excel(filepath, index=False)
print("Excel file written successfully to: ", filepath)
if __name__ == "__main__":
# Read json file, create dataframe, write to excel
jsonData = readJson(filename='transaction-fees.json',)
df = getDataframe(jsonData= jsonData, metricName="transaction-fees")
writeExcel(dataframe= df, filepath='transact.xlsx')
# Read json file, create dataframe, write to excel
jsonData = readJson(filename='hash-rate.json',)
df = getDataframe(jsonData= jsonData, metricName='hash-rate')
writeExcel(dataframe=df, filepath='hash-rate.xlsx')
print("Done writing excel files to current directory ...")
@lydiapuspita
Copy link

Thank you, Mahimai!
it is works! :)

@mahimairaja
Copy link
Author

Glad to know!

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment