"""rec.py: upsert one-line records into the Rebirth version's entities.json (by key, appended before shared_rules).""" import json P = 'resources/data/versions/rebirth/entities.json' def upsert(*records): lines = open(P).read().split('\n') end = next(i for i, l in enumerate(lines) if l.startswith(' ],') or l.startswith(' ]')) for record in records: text = ' ' + json.dumps(record) + ',' at = next((i for i, l in enumerate(lines[:end]) if l.startswith(' {"key": "%s",' % record['key'])), None) if at is not None: lines[at] = text else: lines.insert(end, text) end += 1 # The last record has no comma. last = end - 1 for i in range(1, end): if lines[i].startswith(' {') and not lines[i].endswith(','): lines[i] += ',' lines[last] = lines[last].rstrip(',') open(P, 'w').write('\n'.join(lines)) json.load(open(P))