import re


def _json_remove_excessive_newlines(jstr, ind, n):
    """Remove newline before lines with a certain indent.

    Problem:
    The JSON writer either inserts no newline characters at all, or
    after every entry. The former is impractical, the latter blows up
    JSON files containing large sets of data (e.g. contour coordinates).

    Solution:
    To keep the JSON file structure clear, keep newlines before lines
    with an indent of up to N spaces. Newline characters before every
    line with more indent are removed.

    Arguments:
     - jstr: Indented JSON string.
     - ind: Number of spaces per level indent.
     - n: Lowest level for which newlines are retained.
    """
    # Remove all newlines for >N spaces indent.
    rx1 = "\n {{{n}, }}(?=[^ ])".format(n=n * ind)

    # Remove newline before closing bracket of list entries at indent N
    rx2 = "\n {{{n}}}(?=[\]}}])".format(n=(n - 1) * ind)

    jstr = re.sub(rx1, "", jstr)
    jstr = re.sub(rx2, "", jstr)
    return jstr