Python通过字符串更新json文件

标签 python json

我需要在json中插入一个路径并能够在将来更新,目前的代码是

def save_json(direc):
  try:
    if not os.path.exists('../resources/data.json'):
      os.mknod('../resources/data.json')
      f = open('../resources/data.json', 'a+')
      f.write("{}")
      f.close()
    if os.stat("../resources/data.json").st_size == 0:
      f = open('../resources/data.json', 'a+')
      f.write("{}")
      f.close()
    print(" ")
    #obj.append({"2015":{"08":{"26":{"23365116":{"23365116_15MIN_2015-08-26_23-01.dat":{"dowloaded":"false","moved":"false"}}}}}})
    with open('../resources/data.json', 'r+') as myfile:
      data=myfile.read()
      myfile.close()
    obj = json.loads(data)
    print(direc)

我正在尝试放入这个 json

{"2015":{"08":{"26":{"23365116":{"23365116_15MIN_2015-08-26_23-01.dat":{"downloaded":false,"moved":false}}}}}}

下次我想以某种方式添加这个json,其中我将传递的路径作为参数,即/2015/08/26/23365116/23365116_15MIN_2015-08-26_23-01.dat

({"2015":{"08":{"26":{"23365116":{"23365116_HORARIA_2015-08-26_23-01.dat":{"dowloaded":"false","moved":"false"}}}}}}

最佳答案

将 python 字典保存为 .json

假设您想要将字典保存在变量 my_dict

import json

my_dict = {
  'a': {
    'wow': 'very nice'
  }
}

with open('myJsonFile.json', 'w') as f:
  json.dump(my_dict, f)

使用toolz浏览嵌套字典

toolz 是一个 Python 库,它提供了许多有用的实用函数,特别是如果您想要进行函数式编程,但无论您是否进行函数式编程,所提供的实用函数都可能很有用。我们将使用 toolz.dicttoolz.get_in 函数轻松导航嵌套字典。

from toolz.dicttoolz import get_in

my_dict = {
    '2015': {
        '08': {
            '26': {
                '23365116': {
                    '23365116_15MIN_2015-08-26_23-01.dat': {
                        'downloaded': False, 'moved': False
                    }
                }
            }
        }
    }
}

dict_path = '/2015/08/26/23365116/23365116_15MIN_2015-08-26_23-01.dat'.split('/')
# dict_path is sliced from 1 on wards to avoid the '' since the string starts with a /
res = get_in(dict_path[1:], my_dict)
print('res:', res)

在没有外部库的情况下浏览嵌套字典

如果您不想安装任何其他库,您也可以使用自制的实现

my_dict = {
    '2015': {
        '08': {
            '26': {
                '23365116': {
                    '23365116_15MIN_2015-08-26_23-01.dat': {
                        'downloaded': False, 'moved': False
                    }
                }
            }
        }
    }
}


def get_in(d_path, target_dict, default=None, no_default=False):
    for key in d_path:
        try:
            target_dict = target_dict[key]
        except (KeyError, IndexError):
            if no_default:
                raise
            return default
    return target_dict


dict_path = '/2015/08/26/23365116/23365116_15MIN_2015-08-26_23-01.dat'.split('/')
# dict_path is sliced from 1 on wards to avoid the '' since the string starts with a /
res = get_in(dict_path[1:], my_dict)
print('res:', res)

作为上下文管理器打开

内置函数open是一个上下文管理器,这意味着它支持with语法:

with <context manager> as <res>:
  <wrapped code>

with-syntax 与 open 上下文管理器结合使用,可以让您打开文件,而不必担心关闭文件和处理错误

以下代码:

with open('file-path.ext', 'w') as f:
  # <code>

基本上相当于:

f = open('file-path.ext', 'w')
try:
  # <code>
except Exception as err:
  f.close()
  raise
else:
  f.close()

这就是为什么强烈建议您利用这一点,因为它减少了样板文件,使您的代码更安全、更简洁。

有了这个提示列表,您有望更有效地解决您的问题。我希望这有帮助!

关于Python通过字符串更新json文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59993849/

相关文章:

javascript - 输入 ID 时,将图像添加到来自 json 文件的警报中

javascript - 为什么这个 for in 语句返回 0 和 1?

python - 列的最大值和最小值之间的差异

json - Karate - 如何导入 json 数据

java - 使用 Retrofit 在 JSON 数组上出现空指针异常

python - 弃用警告 : invalid escape sequence - what to use instead of\d?

java - 从 postgres 检索 json 查询并在 java 中显示

python - 使用OpenCV进行垂直曲线检测

python - 使用 Django ORM 查询如何注释是否存在多个级别的外键层次结构

python - 从 Python WMI 获取 CPU 信息