python - 修改json文件

标签 python json

我正在编写一个程序,它会在 api key 超时时更新它们,因此我有一个 json 文件来跟踪所有 api key 以及它们是否处于冷却状态,但我正在努力寻找一种更新“冷却时间”的方法"api key 属性的属性,而无需编辑 api key 属性中包含的数据。

提前感谢您的帮助

import json
import io
import time
import re


def json_Data_Pull():
    file = open('api_Key.json', 'r')
    data = json.load(file)

    return data

#Each api key is assigned a number and when this function is called the specific
#number given in parameters is called, if that number isn't on cooldown, it will
#be returned, otherwise the function will at +1 to that and find another key
def new_Key_Pull(number):
    data = json_Data_Pull()
    arr = []
    try:
        loads = json.loads(data)
        js = json.dumps(loads['api' + number])
        cooldown = re.search(r'("cooldown": "(.*?)")', js, )
        final = re.sub(r'"cooldown": "|"', '' , cooldown.group())
        arr.insert(1, final)
        api = re.search(r'("api(.*)": "(.*?)"})', js, )
        final2 = re.sub(r'"api(.*)": "|"|}', '', api.group())
        arr.insert(2, final2)

        return arr
    except(TypeError):
        pass

#This function sets the current state of an API key to false, and then waits for 62 seconds
#and resetts it to true in order to create a cooldown on each key so that api timeouts
#don't occurr
def cooldown_Key(api):
    loads = json.loads(json_Data_Pull())
    jsd = json.dump(loads)

Json 文件:

"""{
  "api1":{
  "api1": "Num 1",
  "cooldown": "False"
  },
  "api2":{
  "api2": "Num 2",
  "cooldown": "False"
  },
  "api3":{
  "api3": "Num 3",
  "cooldown": "True"
  }
  } """

最佳答案

试试这个:

data = """{
  "api1":{
  "api1": "Num 1",
  "cooldown": "False"
  },
  "api2":{
  "api2": "Num 2",
  "cooldown": "False"
  },
  "api3":{
  "api3": "Num 3",
  "cooldown": "True"
  }
  } """

data = json.loads(data)

# example: modify "api1" cooldown to "True"
data["api1"]["cooldown"] = "True"
print(data)

关于python - 修改json文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52575212/

相关文章:

iphone - 来自 NSString 中保存的字节的 UIImage

python - 使用 Django 下载 xlsx 格式的 SQL 数据

python - 在 Scala 中实现 'yield' 的首选方法是什么?

python - PyTorch FasterRCNN 类型错误 : forward() takes 2 positional arguments but 3 were given

php - 将 Python 生成的数据发送到 PHP 的最佳方式是什么?

javascript - 搜索 javascript 对象中以特定开头的名称

mysql - Yii RESTFul,JSON 格式更新和创建

python - 地铁 python 和 linux

python - 通过 python 对象设置全局 numpy 数组的子部分或切片

javascript - JSON.parse 给我对象而不是结果