我有一个json文本文件和已知的标题名称。
的例子:
[header0]
{
"IPMI": {
"ProtocolEnabled": true,
"Port": 623
},
"SSH": {
"ProtocolEnabled": true,
"Port": 22
}
}
[header1]
{
"GraphicalConsole": {
"ServiceEnabled": true,
"MaxConcurrentSessions": 2
}
}
[header2]
{
"InterfaceEnabled": true,
"SignalType": "Rs232",
"BitRate": "115200",
"Parity": "None",
"DataBits": "8",
"StopBits": "1"
}
我试图创建一个变量(有效载荷)与json下的特定标头与请求模块一起使用。我可以迭代和循环打印数据,没有任何问题。
with open("test.txt") as f:
for line in f:
if line.startswith('[header1]'): # beginning of section use first line
for line in f: # check for end of section breaking if we find the stop line
if line.startswith("[header2]"):
break
else: # else process lines from section
print(line.rstrip("n"))
输出:
{
"GraphicalConsole": {
"ServiceEnabled": true,
"MaxConcurrentSessions": 2
}
}
这是完美的,但我如何创建一个变量与相同的数据?
如果你想要一个你需要的行列表,那么创建一个空列表并添加每个相关的行
with open("test.txt") as f:
reslist = []
for line in f:
if line.startswith('[header1]'): # beginning of section use first line
for line in f: # check for end of section breaking if we find the stop line
if line.startswith("[header2]"):
break
else: # else process lines from section
print(line.rstrip("n"))
reslist.append(line)
return reslist
如果你想输出一个字符串,你可以这样做…
resstring = 'n'.join(reslist)
如果你想收集字典中每个头的输出,请参阅上面的"黑暗骑士"评论
你可以这样做:-
import json
def main(filename):
payload = {}
ch = None
jt = []
with open(filename) as txt:
for line in txt.readlines():
if line.startswith('['):
if ch and jt:
payload[ch] = json.loads(''.join(jt))
jt = []
ch = line[1:line.index(']')]
else:
jt.append(line.strip())
if ch and jt:
payload[ch]=json.loads(''.join(jt))
print(json.dumps(payload, indent=4))
if __name__ == '__main__':
main('test.txt')