python声明 json全局变量
时间: 2023-07-09 07:55:41 浏览: 385
在 Python 中,可以使用 global
关键字声明全局变量,包括 JSON 类型的全局变量。不过需要注意的是,JSON 类型在 Python 中通常是通过字符串表示的,所以在使用前需要进行 JSON 解码操作,可以使用 json
模块提供的 loads
函数将 JSON 字符串解码为 Python 对象。下面是一个例子:
import json
my_json = "{}"
def update_json(key, value):
global my_json
my_dict = json.loads(my_json)
my_dict[key] = value
my_json = json.dumps(my_dict)
update_json("name", "John")
update_json("age", 30)
print(my_json) # 输出 {"name": "John", "age": 30}
在上面的代码中,我们声明了一个空的 JSON 类型的全局变量 my_json
,然后定义了一个函数 update_json
,该函数使用 global
关键字声明了 my_json
变量为全局变量,并在函数内部对其进行了更新。具体来说,我们首先使用 json.loads
函数将 my_json
解码为 Python 字典对象 my_dict
,然后向其中添加一个键值对,最后使用 json.dumps
函数将 my_dict
编码为 JSON 字符串并赋值给 my_json
。最后,我们输出了 my_json
的值,可以看到 my_json
中包含了添加的两个键值对。
相关推荐
















