下面的代码定义了用于转换字段值的字典。读取数据,根据此字典转换一些值,并写入表。它按原样工作。问题是,我现在想将此配置移到.py文件之外的JSON配置文件中。
lookups = {
11: {
"ST1": ["ABC"],
"UNK01": ["125", "ACD"],
"A": ["52"],
"B": ["91"],
"C": ["92"],
"D": ["95"]
},
10: {
"XYZ01": ["91"],
"XYZ02": ["83"],
"XYZ03": ["27"]
}
}
根据jsonlint.com,为了将上述值分配给lookups
是有效的JSON,我必须引用11
和10
键。这样做会破坏我的Python代码并显示TypeError: list indices must be integers, not str
。
如何创建有效的JSON并尽量减少对代码的更改?
答案 0 :(得分:1)
如果要将其转储到json文件:
import json
with open("config.json","w") as f:
json.dump(lookups, f) # dump dict to file
with open("config.json") as f:
s = json.load(f) # load dict from file
print(s)
{'11': {'ST1': ['ABC'], 'A': ['52'], 'D': ['95'], 'UNK01': ['125', 'ACD'], 'B': ['91'], 'C': ['92']}, '10': {'XYZ01': ['91'], 'XYZ03': ['27'], 'XYZ02': ['83']}}
如果你需要按键作为整数,你可以循环和转换为整数或使用pickle
:
import pickle
with open("in.pkl","wb") as f:
pickle.dump(lookups, f)
with open("in.pkl","rb") as f:
s = pickle.load(f)
print(s)
{10: {'XYZ03': ['27'], 'XYZ01': ['91'], 'XYZ02': ['83']}, 11: {'UNK01': ['125', 'ACD'], 'B': ['91'], 'D': ['95'], 'ST1': ['ABC'], 'C': ['92'], 'A': ['52']}}
如果不是按原样使用。
答案 1 :(得分:0)
如果你知道你的密钥是什么类型的数据,那么密钥上的简单int
就足够了:
dictionary_from_json = json.loads(dumped)
newdict = {}
for key, val in dictionary_from_json:
newdict[int(key)] = val
答案 2 :(得分:0)
您可以扩展json.decoder并在可能的情况下将所有键转换为int。
import json
class Json(json.JSONDecoder):
def decode(self,json_string):
default_obj = super(Json,self).decode(json_string)
new_obj = self._rec_serial(default_obj)
return new_obj
def _rec_serial(self,default):
new_dict = {}
for key,value in default.items():
is_dict = isinstance(value,dict)
value = self._rec_serial(value) if is_dict else value
try:
new_dict[int(key)] = value
except ValueError:
new_dict[key] = value
return new_dict
json2= Json()
d = json2.decode(dumped)