Save the SummaryDoc as a json File

Hi everyone,
I am inexperienced with API’s so maybe this has a really simple solution.
I was trying to save the data that I get through the summary.search() function in json format. I am trying to do this because I wish to pass on the summary data into a Matlab script I am working on, and thought using json would be the easiest way to do so. I am open to trying out other formats if they’re more helpful.

I use the following code

list_of_properties=["energy_above_hull",'band_gap','decomposes_to','uncorrected_energy_per_atom','formation_energy_per_atom','material_id','nelements',"density","elements","formula",'is_stable',"uncorrected_energy",'composition','composition_reduced','structure']
#thenext line basically exists so that i can enter a material_id in the console when i run this python script
mat_id=sys.argv.pop()
with MPRester(MP_API_KEY) as mpr:
    Preformatted textyour_material= mpr.summary.search(material_ids=[mat_id],fields=list_of_properties,all_fields=False)[0]
your_material.json()

and get the following error message:
TypeError: Object of type ‘Composition’ is not JSON serializable

I have tried other ways of achieving this , for example:

material_summary=your_material.dict()
json.dumps(material_summary)

which causes the error
TypeError: Object of type Element is not JSON serializable

so if anyone has any tips or suggestion for me I would greatly appreciate it!

Hi @mprester_time,

You can use monty (which is already installed if you are using the MPRester):

from monty.serialization import loadfn, dumpfn

dumpfn(your_object, "your_filename.json") # or .json.gz

This uses the MontyEncoder and MontyDecoder to automatically convert the relevant objects, like Composition, to JSON.

Hope this helps!

Matt

1 Like