Skip to content

Instantly share code, notes, and snippets.

@romgapuz
Created May 18, 2020 07:26
Show Gist options
  • Save romgapuz/c7a4cedb85f090ac1b55383a58fa572c to your computer and use it in GitHub Desktop.
Save romgapuz/c7a4cedb85f090ac1b55383a58fa572c to your computer and use it in GitHub Desktop.
Tool for converting Pickle to JSON using this simple Python Command Line program
"""
Pickle2JSON is a simple Python Command Line program for converting Pickle file to JSON file.
Arguments: Only one (1) argument is expected which is the pickle file.
Usage: python pickle2json.py myfile.pkl
Output: The output is a JSON file bearing the same filename containing the JSON document of the converted Pickle file.
"""
# import libraries
import pickle
import json
import sys
import os
# open pickle file
with open(sys.argv[1], 'rb') as infile:
obj = pickle.load(infile)
# convert pickle object to json object
json_obj = json.loads(json.dumps(obj, default=str))
# write the json file
with open(
os.path.splitext(sys.argv[1])[0] + '.json',
'w',
encoding='utf-8'
) as outfile:
json.dump(json_obj, outfile, ensure_ascii=False, indent=4)
@Red-Satori
Copy link

Works very well. Thank you.

@mcdaqc
Copy link

mcdaqc commented Jul 12, 2023

Ty

@pingsutw
Copy link

how to convert json_obj back to the pickle?

@mcdaqc
Copy link

mcdaqc commented Aug 1, 2023

how to convert json_obj back to the pickle?

# import libraries
import pickle
import json
import sys
import os

# open JSON file
with open(sys.argv[1], 'r', encoding='utf-8') as infile:
    json_str = infile.read()

# convert JSON string to JSON object
json_obj = json.loads(json_str)

# convert JSON object to Pickle object
obj = json_obj

# write the Pickle file
with open(
        os.path.splitext(sys.argv[1])[0] + '.pkl',
        'wb'
    ) as outfile:
    pickle.dump(obj, outfile)

@TharHtetAungg
Copy link

hello how can I convert pkl file to mesh.obj file ?

@ankur-tiger
Copy link

Hi, I am trying to convert pickle object to RDS object, is there a way to convert json to RDS further, to give context, we are building GBM model in python so model object is getting saved as pickle, but due to legacy reasons we have to do deployment in R, looking for a way around here.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment