json 中的所有字母小写

lowercase all the letters in json

我的 json 文件看起来像这样-

{"classes":["BUSINESS","PLACE","HOLD","ROAD","SUB","SUPER","EA","DIS","SUB","UNI"],"annotations":[["Khilg Khil Block A Dha M K Enter House 308/A Road 8 Til Rhy", {"entities": [[0, 8, "EA"], [9, 17, "SUB"], [18, 25, "SUPER"], [26, 31, "DIS"], [32, 46, "BUSINESS"], [47, 58, "HOLDING"], [59, 65, "ROAD"], [66, 75, "SUB"], [76, 82, "PLACE"]]}]

在这种情况下,我想将这里的每个字母都设为小写以获得完整文件。但它不起作用。 我的代码-

data = json.load(open("data.json"))
new_data = {}

for i in new_data.keys():
    if type(new_data[i]) is list:
        new_data[i]=  [j.lower() for j in new_data[i]]
    else:
        new_data[i] = new_data[i].lower()

with open("data.json", 'w') as fp:
    json.dump(new_data, fp)

既然你的数据里有列表的列表,我觉得还是用递归比较好。

代码:

def recursion_lower(x):
    if type(x) is str:
        return x.lower()
    elif type(x) is list:
        return [recursion_lower(i) for i in x]
    elif type(x) is dict:
        return {recursion_lower(k):recursion_lower(v) for k,v in x.items()}
    else:
        return x

data = {'classes': ['BUSINESS', 'PLACE', 'HOLD', 'ROAD', 'SUB', 'SUPER', 'EA', 'DIS', 'SUB', 'UNI'], 'annotations': [['Khilg Khil Block A Dha M K Enter House 308/A Road 8 Til Rhy', {'entities': [[0, 8, 'EA'], [9, 17, 'SUB'], [18, 25, 'SUPER'], [26, 31, 'DIS'], [32, 46, 'BUSINESS'], [47, 58, 'HOLDING'], [59, 65, 'ROAD'], [66, 75, 'SUB'], [76, 82, 'PLACE']]}]]}

new_data = recursion_lower(data)
print(new_data)

输出:

{'classes': ['business', 'place', 'hold', 'road', 'sub', 'super', 'ea', 'dis', 'sub', 'uni'], 'annotations': [['khilg khil block a dha m k enter house 308/a road 8 til rhy', {'entities': [[0, 8, 'ea'], [9, 17, 'sub'], [18, 25, 'super'], [26, 31, 'dis'], [32, 46, 'business'], [47, 58, 'holding'], [59, 65, 'road'], [66, 75, 'sub'], [76, 82, 'place']]}]]}