如何在不将完整的json加载到python中的情况下更新json文件中键的值? [英] How to update the value of a key in a json file without loading the complete json in python?

查看:206
本文介绍了如何在不将完整的json加载到python中的情况下更新json文件中键的值?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

考虑一下,更新之前的json文件的内容是

Consider, the content of json file before the update is,

{"key1": "value A", "key2": "value B"}

我想将key1更新为值C,而无需使用json.load()实际打开json文件.所以最终输出应该是

I want to update the key1 to value C without actually opening the json file using json.load(). So the final output should be,

{"key1": "value C", "key2": "value B"}

我想要mongoDB中的update()之类的东西.有可能通过任何图书馆吗?

I want something like update() in mongoDB. Is it possible through any library?

推荐答案

这全都取决于任务的上下文.正如我在评论中告诉的那样,您可以使用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) + '}')

这篇关于如何在不将完整的json加载到python中的情况下更新json文件中键的值?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆