I have a flat parquet file where one varchar columns store JSON data as a string and I want to transform this data to a nested structure, i.e. the JSON data becomes nested parquet. I know the schema of the JSON in advance if this is of any help.
Here is what I have "accomplished" so far:
Building the sample data
# load packages
import pandas as pd
import json
import pyarrow as pa
import pyarrow.parquet as pq
# Create dummy data
# dummy data with JSON as string
person_data = {'Name': ['Bob'],
'Age': [25],
'languages': "{'mother_language': 'English', 'other_languages': ['German', 'French']}"
}
# from dict to panda df
person_df = pd.DataFrame.from_dict(person_data)
# from panda df to pyarrow table
person_pat = pa.Table.from_pandas(person_df)
# save as parquet file
pq.write_table(person_pat, 'output/example.parquet')
Script proposal
# load dummy data
sample = pa.parquet.read_table('output/example.parquet')
# transform to dict
sample_dict = sample.to_pydict()
# print with indent for checking
print(json.dumps(sample_dict, sort_keys=True, indent=4))
# load json from string and replace string
sample_dict['languages'] = json.loads(str(sample_dict['languages']))
print(json.dumps(sample_dict, sort_keys=True, indent=4))
#type(sample_dict['languages'])
# how to keep the nested structure when going from dict —> panda df —> pyarrow table?
# save dict as nested parquet...
So, I here are my specific questions:
- Is this approach the way to go or can it be optimised in any way? All the transformations between dict, df and pa table does not feel efficient, so happy to get educated here.
- How can I preserve the nested structure when doing the dict —> df transformation? Or is this not needed at all?
- What is the best way to write the nested parquet file? I have read Nested data in Parquet with Python and here fast parquet is mentioned for reading but with lacking writing capability - is there any working solution in the meantime?