简体   繁体   English

使用 python 将 api 数据保存到 json 文件中

[英]saving api data into a json file using python

I have some python files, which consist of functions.我有一些 python 文件,它们由函数组成。 I have another python file let it be sample.py, where I will be calling those functions, so whenever I am calling the functions, the information from the function should be saved into an external JSON file.我还有另一个 python 文件,让它成为 sample.py,我将在其中调用这些函数,所以每当我调用这些函数时,来自 function 的信息应保存到外部 Z0ECD11C1D7A287401D148A23BBD72A 文件中。 Example:例子:

    def Addtext(Text, TextColor=(0,0,0), TextLevel=5):
        pass

This is the function which I will be calling in my sample.py.这是我将在我的 sample.py 中调用的 function。 so whenever the function is called, the information inside the function, that can be anything, such as Text Text-color, text level, should be taken and saved into a JSON file.因此,每当调用 function 时,function 中的信息,可以是任何东西,例如文本文本颜色,文本级别,都应该被保存到 Z0ECD11C1D7A287401D148A23ZD7 文件中。 so whenever the function is hit the information should be saved into a JSON file.因此,每当命中 function 时,信息应保存到 JSON 文件中。

Have you tried the usage of a decorator?您是否尝试过使用装饰器? It would add the "save" functionality for each function that is going to be called and needed to save to json.它将为每个将被调用并需要保存到 json 的 function 添加“保存”功能。

An eg:例如:

import json

def saving_to_json(func):
    def wrapper():
        data_to_save = func()
        with open('saved_data.json', 'a') as outfile:
            json.dump(data_to_save, outfile)
            outfile.write('\n')
    return wrapper

@saving_to_json
def add_text():
    data = {"Test 123": "Hello"}
    print(data)
    return data

add_text()

Not the focus of the answer, but as an advice, in python "usually" variables and function names are snake cased.不是答案的重点,但作为建议,在 python “通常”变量和 function 名称是蛇形的。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM