I have an excel file with a structure as the following:
Title | List |
---|---|
Title_1 | [‘str_1’, ‘str_2’] |
Title_2 | [‘str_3’, ‘str_4’] |
and I want to get the data in a json structure as:
{"0":{"Title": "Title_1", "List": ['str_1', 'str_2']}, "1":{"Title": "Title_2", "List": ['str_3', 'str_4']}}
instead of:
{"0":{"Title": "Title_1", "List": "['str_1', 'str_2']"}, "1":{"Title": "Title_2", "List": "['str_3', 'str_4']"}}
How can I achieve this by using the pandas module in python?
I have tried:
df = pd.read_excel("my_excel.xlsx")
df.to_dict("index")
and get:
{"0":{"Title": "Title_1", "List": "['str_1', 'str_2']"}, "1":{"Title": "Title_2", "List": "['str_3', 'str_4']"}}
2
Answers
To get your desired datatype you can try the following transformation:
This function simply takes a string value and do the following:
ValueError
orSyntaxError
it will return the original string valueIf you want to use the
pandas
library, you can use the Dataframe methodto_json
. This will give you the JSON structure of the dataframe.To validate the result you can use: