Home > other >  How to convert JSON to a dataframe with python
How to convert JSON to a dataframe with python

Time:10-17

How do I open a json file and turn it into a dataframe? I want to create graphs with Plotly later but I cannot seem to create a dataframe.

def open_file(filename):
  with open(filename, "r") as file:
    file_list = json.load(file)
    output_df = pd.DataFrame(file_list)
    return output_df


open_file("LT.json")

The error I get:

ValueError("DataFrame constructor not properly called!")

CodePudding user response:

The error ValueError("DataFrame constructor not properly called!") is telling you that you passed the incorrect type of data to the DataFrame. So, most probably file_list is not a dictionary. In my case, your code is 100% working. So, I think the problem is definitely from the JSON file. Maybe file_list is a type of string. If that is the case, using the eval method might help.

output_df = pd.DataFrame(eval(file_list))

But using pandas.read_json works 99% of the time

output_df = pd.read_json(filename)
  • Related