读取带有标题的JSON文本文件,并仅将指定标题下的数据检索到Python中的变量中

2024-09-30 08:35:27 发布

您现在位置:Python中文网/ 问答频道 /正文

我有一个包含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
  }
}

这很完美,但是我如何创建具有相同数据的变量呢


Tags: 数据injsontrueforifportline
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)

如果您想收集dict中每个标题的输出,请参阅上面的“DarkKnight”注释

你可以这样做:-

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')

相关问题 更多 >

    热门问题