0

screenshot of desired formatting change

So I am trying to modify some json file and I want to be consistent with its own style. I managed to handle order of keys, separators, etc, but I can't print empty list across few lines (see diff image above).

Here's the code snippet I have for this task.

info = json.load(f, object_pairs_hook=OrderedDict)
# make some changes in info
f.seek(0)
f.write(json.dumps(info, separators=(',', ': '), indent=4))
f.truncate()

I thought about a workaround using .replace("[],", "[\n\n\t],"), but it's kinda dirty (and incorrect for nested stuff). Any better way to do this? (or I am missing something in the json module?)

martineau
  • 119,623
  • 25
  • 170
  • 301
Uduse
  • 1,491
  • 1
  • 13
  • 18
  • You may be able to use a (modified version) of the custom `JSONEncoder` along with the `NoIndent` class as shown in [this answer](http://stackoverflow.com/a/42721412/355230). – martineau Mar 25 '17 at 02:44

2 Answers2

1

You can update the data by adding a special string to every empty list. Then you might end up with a file containing this:

"configs": [
    "MAGIC_VALUE_NOBODY_USES"
],

Then just remove the lines that contain "MAGIC_VALUE_NOBODY_USES".

John Zwinck
  • 239,568
  • 38
  • 324
  • 436
1

You can modify the json module on your own, simply change json/encoder.py.

The function _make_iterencode is the key for the output, modify the local function _iterencode_list,

def _iterencode_list(lst, _current_indent_level):
    if not lst:
        if _indent is not None:
            yield '[' + '\n' + (' ' * (_indent * _current_indent_level)) + ']'
        else:
            yield '[]'
        return
    # ... 
Qiang Jin
  • 4,427
  • 19
  • 16