我有一个 json 文件,其中包含不同的 2 个分层列表。在主列表的每个元素之后,我添加了一个换行符,以便您可以轻松读取数据。但是当我加载文件并对列表中的某些元素进行更改并将其转储回时,缩进被弄乱了,您无法再阅读它。那么我该如何制作它以便在之后有一个换行符列表第一层的每个元素都像之前而不是在第二层列表的每个元素之后?谢谢你帮助我!
我的代码:
with open("./world_data.json", "r") as f:
data = json.load(f)
new_data = data[level_name] #Accessing the right variable in the json ("level_1_data/"level_2_data")
new_data[button[1][3][1]][button[1][3][0]] = world.block_number #Making changes to the lists
data[level_name] = new_data
data.update(data)
with open("./world_data.json", "w") as f:
json.dump(data, f, indent=4)
倾销之前(我希望它在倾销后的样子):
{
"level_1_data": [
[1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1],
[1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1],
[1, 0, 0, 0, 0, 7, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 8, 1],
[1, 0, 0, 0, 0, 2, 0, 0, 0, 0, 0, 7, 0, 0, 0, 0, 0, 2, 2, 1]
],
"level_2_data": [
[1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1],
[1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1],
[1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1],
[1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1],
[1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1]
}
转储后(我把大部分数据都留下了,因为它太长了):
{
"level_1_data": [
[
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1
],
[
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
1
]
}
我不确定是否可以使用 json 库以您想要的格式保存文件。我使用的一个肮脏的技巧是将 json.dumps 对象假设为字符串并执行一些 str 替换以根据需要格式化数据。
请尝试以下代码:
dict = data
def format_json(data):
digits = [0,1,2,3,4,5,6,7,8,9]
for i in digits:
i = str(i)
data = data.replace((i+',\n'), (i+',')) # remove \n after digit and comma
data = data.replace(', ', ',') # remove unwanted space
data = data.replace(('\n '+i), i) # remove \n and unwanted space before digit
data = data.replace((i+'\n '), i) #remove unwanted space and \n after digit
data = data.replace(',', ', ') # add space after comma for readability
return data
final = format_json(json.dumps(dict, indent=4))
with open('final.json', 'w') as f:
f.write(final)
# checking if the file is parsable
with open('final.json', 'r') as f:
data = json.load(f)
print(data['level_1_data'])
json 文件将根据需要保存,保存后也可以加载。请注意 format_json 特定于上述请求格式的数据。
输出文件(final.json):
{
"level_1_data": [
[1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1],
[1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1],
[1, 0, 0, 0, 0, 7, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 8, 1],
[1, 0, 0, 0, 0, 2, 0, 0, 0, 0, 0, 7, 0, 0, 0, 0, 0, 2, 2, 1]
],
"level_2_data": [
[1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1],
[1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1],
[1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1],
[1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1],
[1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1]
]
}
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句