如何使用JSON编码全局Python变量?

Win*_*ter 2 python global-variables

我试图弄清楚如何将全局变量编码为JSON格式,我什至不确定是否可行。我正在使用Python 2.7.8,并且已经尝试了几种不同的方法:

# Variables
value = "String" # String
value2 = 0 # Integer
value3 = True # Boolean

json.dumps({"key": value, "key2": value2, "key3": value3}, sort_keys=True, indent=4, separators=(',', ': '))
Run Code Online (Sandbox Code Playgroud)

我还尝试过先将其设置为字符串(带或不带花括号,在字符串值上带/不带引号等)。

json_raw = '{"key": %s, "key2": %d, "key3": %s}' % (value, value2, value3)
json.dumps(json_raw, sort_keys=True, indent=4, separators=(',', ': '))
Run Code Online (Sandbox Code Playgroud)

但是,通过这些尝试中的每一项,我都会收到错误消息:

AttributeError: 'str' object has no attribute 'dumps'
Run Code Online (Sandbox Code Playgroud)

有任何想法吗?

Tym*_*aul 5

让我用代码回答:

value = "String" # String
value2 = 0 # Integer
value3 = True # Boolean
json_map = {}
json_map["Some string"] = value
json_map["Some int"] = value2
json_map["Some bool"] = value3
result = json.dumps(json_map)
Run Code Online (Sandbox Code Playgroud)

然后结果包含'{"Some int": 0, "Some string": "String", "Some bool": true}'。这一切都归功于python字典json.dumps的神奇魅力