0

I'm new on stack-overflow.

I'm trying to convert pkl file into json file using python. Below is my sample code

import pickle
import pandas as pd

# Load pickle file
input_file = open('file.pkl', 'rb')
new_dict = pickle.load(input_file)
input_file()

# Create a Pandas DataFrame
data_frame = pd.DataFrame(new_dict)

# Copy DataFrame index as a column
data_frame['index'] = data_frame.index

# Move the new index column to the from of the DataFrame
index = data_frame['index']
data_frame.drop(labels=['index'], axis=1, inplace = True)
data_frame.insert(0, 'index', index)

# Convert to json values
json_data_frame = data_frame.to_json(orient='values', date_format='iso', date_unit='s')
with open('data.json', 'w') as js_file:
    js_file.write(json_data_frame)

When I run this code I got error that TypeError: '_io.TextIOWrapper' object is not callable. By following some same issues This one and This one, these issues suggested to use write method with input_file() at line 7 but still I'm getting this error io.UnsupportedOperation: write which is probably a writing method but I'm using it with reading and for reading I'm unable to fine any method. I also tried to read pickle file in following way

with open ('file.pkl', 'rb') as input_file:
    new_dict = pickle.load(input_file)

and I'm getting this error

DataFrame constructor not properly called!. 

I need some kind suggestions that how I can solve this problem? Any suggestions about other tools which can perform this task, will be appreciable. Thanks

MegaIng
  • 7,361
  • 1
  • 22
  • 35
Erric
  • 123
  • 1
  • 10
  • 1
    What is the pickled object in `file.pkl`? And what was the purpose of this line `input_file()`? I think you were looking for `input_file.close()`. – dspencer Mar 30 '20 at 07:13
  • 1
    For better understanding here is my pkl dictionary data. {1: {'pose': array([-3.101, 0.014, 0.022], dtype=float32), 'betas': array([0.073, -0.319, -0.114], dtype=float32)}}. There are two main objects, pose data and betas data. – Erric Mar 30 '20 at 07:23
  • Can you please follow this [link](https://stackoverflow.com/questions/39257147/convert-pandas-dataframe-to-json-format) and check if it solves your problem. Thanks. – Rishab P Mar 30 '20 at 15:16
  • Thank you guys for your response. I have solve my problem. The problem was due to serialization. JSON format is quite different and built-in json module can only handle primitives types that have a direct JSON equivalent (lists, dictionary, strings etc.) so I used JSONEncoder to solve this problem. – Erric Mar 31 '20 at 07:52
  • 2
    please answer your own quest. Otherwise this post will be found if someone searches for questions without answers. – Andreas May 20 '21 at 09:25

0 Answers0