dimid
dimid

Reputation: 7649

Preserve formatting when processing JSON

I'd like to load a JSON file, modify it, and save the results, without altering the original formatting. I.e. something like this:

 json_hash = JSON.parse(File.read('my.ipynb'))
 [...] # modify
 JSON.dump(json_hash, File.open('my.ipynb', 'wt'))

In this answer JSON.pretty_generate is suggested, but how do I retrieve pretty_generates options (e.g. object_nl) when parsing the original JSON?

P.S. in case it's relevant the JSON file is a Jupyter notebook.

Upvotes: 1

Views: 1272

Answers (1)

dimid
dimid

Reputation: 7649

I originally wanted to use ruby since it has the useful dig method, but I ended up implementing dig in python, so I can use the nbformat package. I.e.

import nbformat

file = 'my.ipynb'
nb = nbformat.read(file, 4)
[...] #  modify
nbformat.write(nb, open(file, 'wt'))

Upvotes: 1

Related Questions