Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get pretty printed JSON with Keras model.to_json()?

Tags:

python

json

keras

I am trying to save model to JSON with Keras and getting condensed JSON code.

Is it possible to save in pretty-printed human friendly JSON here?

like image 377
Suzan Cioc Avatar asked Jul 26 '17 15:07

Suzan Cioc


2 Answers

The to_json method from keras accepted **kwargs and passed them to json.dumps. Therefore this is the one line solution:

print(model.to_json(indent=4))

It generate results similar to the example of @anton-vbr.

like image 147
Philip Tzou Avatar answered Nov 15 '22 16:11

Philip Tzou


You can use pprint.pformat to retrieve a pretty string:

import pprint
json_str = model.to_json()
formatted_str = pprint.pformat(json.loads(json_str), indent=4)

If you don't want to save a copy of the formatted json, rather if you prefer to save it to a file, you can use pprint.pprint and specify stream=... with a file handler:

pprint.pprint(json.loads(json_str), indent=1, stream=open('model.json', 'w'))
like image 36
cs95 Avatar answered Nov 15 '22 17:11

cs95