Skip to content Skip to sidebar Skip to footer

How To Update The Value Of A Key In A Json File Without Loading The Complete Json In Python?

Consider, the content of json file before the update is, {'key1': 'value A', 'key2': 'value B'} I want to update the key1 to value C without actually opening the json file using j

Solution 1:

It all depends on the context of the task. As I told in comment, you can use SAX parser instead of DOM. It will prevent you from building huge model in memory. SAX parsers work on event (callback)-driven mechanisms.

Another option, if your JSON structure is as simple as shown and is not expected to change, you can use simply regular expressions. The following example shows the idea, but be careful, it assumes, your values are always in form [\w\d\s]* and do not contains quotes and commas.

import re

rx = r'\s*\"(\w\d+)\"\s*:\s*"([\w\d\s]*)"\s*'withopen('in.json') as inp:
  src_text = inp.read().strip(' \t\r\n{}')
  output = []
  for pair in src_text.split(','):
      m = re.match(rx, pair)
      key = m.group(1)
      val = m.group(2)
      output.append('"{}": "{}"'.format(key, 'value C'if key == 'key1'else val))
  withopen('out.json', 'w') as outp:
      outp.write('{' + ', '.join(output) + '}')

Post a Comment for "How To Update The Value Of A Key In A Json File Without Loading The Complete Json In Python?"