我正在尝试验证 json 文件,验证后我想将结果写入新文件。 为此,我在 python 中使用 json 模块。我有一个名为 schema 的字典对象,它包含所有键和值。如果我打印它,我得到的结果如下所示
{'deviceId': 'String', 'userId': 'String', 'regTime': 'Number', 'timestamp': 'String', 'cardiac': 'Number', 'gyro': 'array', 'acc': 'array'}
我想根据占位符 @schema_result 将整个架构结果写入一个文件中。如下所示
deviceId String
userId String
regTime Number
timestamp String
cardiac Number
gyro array
acc array
目前我正在像这样编写这个模式对象
def filing(schema, file_name): #a function that takes schema dictionary and name of file where to write
config = open(file_name, 'w')
for line in open('schema.json', 'r'):
for key,value in schema.items():
print(key+" "+value+"\n")
line = line.replace('@schema_result', str(key+" "+value+"\n"))
config.write(line)
这只会导致将第一个键和值替换为@schema_result。由于模式对象是字典,我无法添加下一个项目,因为在第一次迭代后,它将用第一个键和值替换@schema_result,下次它找不到@schema_result,因为它已经被替换。
当前结果如下
deviceId String #against @schema_placeholder in first iteration
如何针对文件中的一个占位符写入所有键和值
有两个文件
-
schema.json
是包含占位符@schema_result的文件 - 这个
@schema_result
被新文件中的输出替换为file_name
变量
最佳答案
您可以使用带有 join
的列表理解来连接整个字典,而不是使用 for
循环从 schema
字典中读取每个项目键值放在一起,然后将其写入文件,
schema = {'deviceId': 'String', 'userId': 'String', 'regTime': 'Number', 'timestamp': 'String', 'cardiac': 'Number', 'gyro': 'array', 'acc': 'array'}
formatted_schema = ["{} {}\n".format(k,v) for k,v in schema.items()]
formatted_schema = ''.join(formatted_schema)
# output,
deviceId String
userId String
regTime Number
timestamp String
cardiac Number
gyro array
acc array
现在您只需将 formatted_schema
写入文件即可将其替换为 @schema_result
关于python - 如何根据文件中的一个占位符写入字典键和值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53029767/