读取文本文件时为空的json对象

时间:2019-05-27 04:39:22

标签: python json text

我正在测试带有文本数据的python脚本。可以运行脚本并返回有效的json文件(如果文本包含在脚本中),但是运行脚本时使用单独的文本文件时却得到了空的json对象。

仅输出空的json文件

{
  "ospf": []
}

下面的代码在使用读取的文本文件运行时返回空的json对象

import json

result = {}
l = []

with open('data.txt') as myf:
   for i in myf:
     if i:
        p = [parameter for parameter in i.split("*")]
        for line, x in enumerate(p[0].split("\n")):
            if x and "Ls id" in x:
                ls_id, ip = x.split(": ")
                ls_id = ls_id.strip()
                ip = ip.strip()
        for y in p[1:]:
            if y and "P-2-P" in y:
                temp = {ls_id:ip}
                for items in y.split("\n"):
                    try:
                        key, value = items.split(": ")
                        key = key.strip()
                        value = value.strip()
                        temp[key] = value
                    except ValueError:
                       pass
                l.append(temp)
result["ospf"] = l
print (json.dumps(result,indent=2))

with open('data.json', 'w') as json_file:
    json.dump(result, json_file)

执行以下带有文本数据的ok代码后,作为数据..没问题

import json

data = '''
  Type      : Router
  Ls id     : 1.1.1.2
  Adv rtr   : 1.1.1.2
  Ls age    : 201
  Len       : 84
  Link count: 5
   * Link ID: 1.1.1.2
     Data   : 255.255.255.255
     Link Type: StubNet
     Metric : 1
     Priority : Medium
   * Link ID: 1.1.1.4
     Data   : 192.168.100.34
     Link Type: P-2-P
     Metric : 1
   * Link ID: 192.168.100.33
     Data   : 255.255.255.255
     Link Type: StubNet
     Metric : 1
     Priority : Medium
   * Link ID: 1.1.1.1
     Data   : 192.168.100.53
     Link Type: P-2-P
     Metric : 1
   * Link ID: 192.168.100.54
     Data   : 255.255.255.255
     Link Type: StubNet
     Metric : 1
     Priority : Medium

  Type      : Router
  Ls id     : 1.1.1.1
  Adv rtr   : 1.1.1.1
  Ls age    : 1699
  Len       : 96
  Options   :  ASBR  E
  seq#      : 80008d72
  chksum    : 0x16fc
  Link count: 6
   * Link ID: 1.1.1.1
     Data   : 255.255.255.255
     Link Type: StubNet
     Metric : 1
     Priority : Medium
   * Link ID: 1.1.1.1
     Data   : 255.255.255.255
     Link Type: StubNet
     Metric : 12
     Priority : Medium
   * Link ID: 1.1.1.3
     Data   : 192.168.100.26
     Link Type: P-2-P
     Metric : 10
   * Link ID: 192.168.100.25
     Data   : 255.255.255.255
     Link Type: StubNet
     Metric : 10
     Priority : Medium
   * Link ID: 1.1.1.2
     Data   : 192.168.100.54
     Link Type: P-2-P
     Metric : 10
   * Link ID: 192.168.100.53
     Data   : 255.255.255.255
     Link Type: StubNet
     Metric : 10
     Priority : Medium'''

import json

result = {}
l = []
for i in data.split("\n\n"):
    if i:
        p = [parameter for parameter in i.split("*")]
        for line, x in enumerate(p[0].split("\n")):
            if x and "Ls id" in x:
                ls_id, ip = x.split(": ")
                ls_id = ls_id.strip()
                ip = ip.strip()
        for y in p[1:]:
            if y and "P-2-P" in y:
                temp = {ls_id:ip}
                for items in y.split("\n"):
                    try:
                        key, value = items.split(": ")
                        key = key.strip()
                        value = value.strip()
                        temp[key] = value
                    except ValueError:
                       pass
                l.append(temp)
result["ospf"] = l
print (json.dumps(result,indent=2))

with open('data.json', 'w') as json_file:
    json.dump(result, json_file)

我不确定我做错了什么。请进一步告诉我。谢谢。

1 个答案:

答案 0 :(得分:0)

一种简单的解决方法是将文件合并为一个大字符串。那么您的代码将按预期工作。绝对不是一个干净的答案,但是您可以让其余代码保持不变。

import json

result = {}
l = []

with open('data.txt') as myf:

    a = ''.join(myf)
    for i in a.split("\n\n"):
     if i:
        p = [parameter for parameter in i.split("*")]
        for line, x in enumerate(p[0].split("\n")):
            if x and "Ls id" in x:
                ls_id, ip = x.split(": ")
                ls_id = ls_id.strip()
                ip = ip.strip()
        for y in p[1:]:
            if y and "P-2-P" in y:
                temp = {ls_id:ip}
                for items in y.split("\n"):
                    try:
                        key, value = items.split(": ")
                        key = key.strip()
                        value = value.strip()
                        temp[key] = value
                    except ValueError:
                       pass
                l.append(temp)
result["ospf"] = l
print (json.dumps(result,indent=2))
with open('data.json', 'w') as json_file:
    json.dump(result, json_file)