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?)

1
  • You may be able to use a (modified version) of the custom JSONEncoder along with the NoIndent class as shown in this answer. Commented Mar 25, 2017 at 2:44

2 Answers 2

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".

Sign up to request clarification or add additional context in comments.

Comments

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
    # ... 

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.