error says it a Pandas DataFrame when dumping a Python dict

Viewed 121

I have a Python dictionary, but when I try to dump it as a JSON file, it says it is a Pandas DataFrame!

import pandas as pd
import os
import re
import json

files_net = [f for f in os.listdir('.') if re.match(r'network_.+.json', f)]
    
networks = {}
for file in files_net:
    with open(file) as f:
        networks[re.search(r'network_(.+).json', file).group(1)] = pd.read_json(f)
type(networks)

>>> dict

with open('networks.json', 'w') as f:
    json.dump(networks, f)

TypeError: Object of type DataFrame is not JSON serializable
1 Answers

Yes networks is a dictionary, but values of it are pd.DataFrames because they come from pd.read_json; hence the error. You might try to_json whilst forming the key-value pairs:

networks[re.search(r'network_(.+).json', file).group(1)] = pd.read_json(f).to_json()

But since you are reading json anyway, you might use json module in the first place e.g. json.load(f).

Related