import re
import json


def clean_qstat_json(stream):
    """
    Clean up the improperly escaped JSON returned by qstat
    """
    string_entry_re = re.compile(r'^\s*"(?P<key>.+)":"(?P<value>.+)"(?P<comma>,?)$')

    lines = []

    for line in stream.splitlines():
        match = string_entry_re.match(line)
        if match is not None:
            fixed_value = json.dumps(match.group('value'))
            line = f'"{match.group("key")}":{fixed_value}{match.group("comma")}'

        lines.append(line)

    return json.loads(''.join(lines))