且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

如何在不将完整的json加载到python中的情况下更新json文件中键的值?

更新时间:2023-09-10 20:11:10

这全都取决于任务的上下文.正如我在评论中告诉的那样,您可以使用SAX解析器而不是DOM.这将阻止您在内存中构建巨大的模型. SAX解析器使用事件(回调)驱动的机制.

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.

另一种选择,如果您的JSON结构如图所示那样简单,并且预计不会发生变化,则可以仅使用正则表达式.下面的示例说明了这种想法,但是要小心,它假定您的值始终采用[\w\d\s]*形式,并且不包含引号和逗号.

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*'

with open('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))
  with open('out.json', 'w') as outp:
      outp.write('{' + ', '.join(output) + '}')