简体   繁体   English

如何通过逐行读取文件来制作json字符串?

[英]How to make a json string by reading file line by line?

I have a file like this: 我有一个像这样的文件:

machineA=1.2.3.4.5
machineB=2.5.7.8.9

I need to read above file and make a string like this for each line: 我需要阅读上面的文件,并为每一行创建一个像这样的字符串:

{"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"}

As you can see in my above json string only value of server and ip is changing and other remaining two keys, it's value stays same always. 正如您在我上面的json字符串中看到的那样,仅serverip值正在更改,而其他两个键的值始终保持不变。 How can I generate a string like this for each line? 如何为每一行生成这样的字符串?

I am not able to figure out how to make correspoding json for each line and print them out on the console. 我无法弄清楚如何使每行对应的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()

I'd suggest making a dictionary then using the built in json module to convert it to a JSON string, because I find that cleaner to read. 我建议先制作一个字典,然后使用内置的json模块将其转换为JSON字符串,因为我发现该阅读器更干净。

import json

mydict = {
    "test": "hello world.",
    "server": machine,
    "ip": ip,
    "reason": "data"
 }
 json.dumps(mydict)

See Robᵩ's answer for how to do it without the json module 请参阅Robᵩ的答案 ,了解如何在没有json模块的情况下执行此操作

You don't have to use the JSON library just because the output format is JSON. 不必使用JSON库只是因为输出格式为JSON。 Try one of these: 尝试以下方法之一:

output_line = '{"test":"hello world.","server":"%s","ip":"%s","reason":"data"}'%(
    machine, ip)
output_line = '{{"test":"hello world.","server":"{}","ip":"{}","reason":"data"}'.format(
    machine, ip)
output_line = f'{{"test":"hello world.","server":"{machine}","ip":"{ip}","reason":"data"}'

Note that the final line only works on recent versions of Python3. 请注意,最后一行仅适用于最新版本的Python3。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM