我有这样一个文件:
machineA=1.2.3.4.5
machineB=2.5.7.8.9
我需要阅读上面的文件并为每一行制作一个这样的字符串:
{"test":"hello world.","server":"machineA","ip":"1.2.3.4.5","reason":"data"}
{"test":"hello world.","server":"machineB","ip":"2.5.7.8.9","reason":"data"}
正如您在我上面的 json 字符串中看到的,只有 server
和 ip
的值在变化,其他两个键的值始终保持不变。如何为每一行生成这样的字符串?
我不知道如何为每一行制作相应的 json 并在控制台上打印出来。
f = open('hosts.txt')
line = f.readline()
while line:
print(line)
machine=line.split("=")[0]
ip=line.split("=")[1]
# now how to make a json string for each line
line = f.readline()
f.close()
最佳答案
我建议创建一个字典,然后使用内置的 json
模块将其转换为 JSON 字符串,因为我发现这样更易读。
import json
mydict = {
"test": "hello world.",
"server": machine,
"ip": ip,
"reason": "data"
}
json.dumps(mydict)
参见 Robᵩ's answer了解如何在没有 json
模块的情况下做到这一点
关于python - 如何通过逐行读取文件来制作json字符串?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50518293/