不能解析json文件,说没有JSON对象可以被解码

我有一个JSON转储为

{
  "alarm": [
    {
      "ackId": 16,
      "count": 1,
      "description": "<p>A SSH outage was identified on interfacen      10.21.5.39.</p> <p>A new Outage record has beenn      created and service level availability calculations will ben      impacted until this outage is resolved.</p>",
      "firstEventTime": 1495277308427,
      "id": 16,
      "ifIndex": null,
      "ipAddress": "10.21.5.39",
      "lastEvent": {
        "createTime": 1495277308437,
        "description": "<p>A SSH outage was identified on interfacen      10.21.5.39.</p> <p>A new Outage record has beenn      created and service level availability calculations will ben      impacted until this outage is resolved.</p>",
        "display": "Y",
        "host": "opennms",
        "id": 625,
        "ifIndex": null,
        "ipAddress": "10.21.5.39",
        "log": "Y",
        "logMessage": "SSH outage identified on interface 10.21.5.39 with reason code: Connection refused (Connection refused).",
        "nodeId": 9,
        "nodeLabel": "fra01-api-01",
        "parameters": [
          {
            "name": "eventReason",
            "type": "string",
            "value": "Connection refused (Connection refused)"
          }
        ],
        "serviceType": {
          "id": 5,
          "name": "SSH"
        },
        "severity": "MINOR",
        "source": "OpenNMS.Poller.DefaultPollContext",
        "time": 1495277308427,
        "uei": "uei.opennms.org/nodes/nodeLostService"
      },
      "lastEventTime": 1495277308427,
      "logMessage": "SSH outage identified on interface 10.21.5.39 with reason code: Connection refused (Connection refused).",
      "managedObjectInstance": null,
      "managedObjectType": null,
      "nodeId": 9,
      "nodeLabel": "fra01-api-01",
      "ossPrimaryKey": null,
      "parameters": [
        {
          "name": "eventReason",
          "type": "string",
          "value": "Connection refused (Connection refused)"
        }
      ],
      "qosAlarmState": null,
      "reductionKey": "uei.opennms.org/nodes/nodeLostService::9:10.21.5.39:SSH",
      "serviceType": {
        "id": 5,
        "name": "SSH"
      },
      "severity": "MINOR",
      "suppressedTime": 1495277308427,
      "suppressedUntil": 1495277308427,
      "type": 1,
      "uei": "uei.opennms.org/nodes/nodeLostService",
      "x733AlarmType": null,
      "x733ProbableCause": 0
    }
  ],
  "count": 1,
  "offset": null,
  "totalCount": 1
}

我写了一个小代码从json获取一些细节

def get_nodes_opennms():
    headers={'Accept': 'application/json' }
    x = requests.get('http://localhost:8980/opennms/rest/alarms?comparator=ge&severity=MINOR?limit=0',headers=headers , auth=('admin', 'Op3AD'))
    parsed = json.loads(x.content)
    #print json.dumps(parsed, indent=4, sort_keys=True)
    wriet_me_to_file = json.dumps(parsed, indent=4, sort_keys=True)
    f=open('out.txt', 'w')
    f.write(wriet_me_to_file)
    for i in json.load(open('out.txt'))["alarm"]:
        try:
            print (["ipAddress"])
            print (["logMessage"])
        except Exception as e:
          print "something is wrong"

这是抛出我的错误:

Traceback(最近一次调用的最后一个):文件“python_opennms.py”,第24行,位于x = get_nodes_opennms()文件“python_opennms.py”,第15行,位于get_nodes_opennms for i in json.load(open('out.txt' ))[ “报警”]:文件“/usr/lib/python2.7/json/ INIT py”为,线291,在负载**千瓦)文件“/usr/lib/python2.7/json/ INIT。 py“,第339行,在加载时返回_default_decoder.decode(s)文件”/usr/lib/python2.7/json/decoder.py“,第364行,在decode obj中,end = self.raw_decode(s,idx = _w(s,0).end())在raw_decode文件“/usr/lib/python2.7/json/decoder.py”,第382行raise ValueError(“没有JSON对象可以被解码”)ValueError:No JSON对象可以被解码

有人可以帮忙吗?


您正在打开写入后未关闭的文件。 可能系统没有完全刷新流缓冲区到磁盘,所以open('out.txt')遇到文件不完整的内容。

最好和最安全的方法是:

with open('out.txt', 'w') as f:
    f.write(wriet_me_to_file)
for i in json.load(open('out.txt'))["alarm"]:
链接地址: http://www.djcxy.com/p/48681.html

上一篇: Not able to parse a json file, says No JSON object could be decoded

下一篇: How to get location from get value json in python?