【问题标题】:Filter and print Json output过滤并打印 Json 输出
【发布时间】:2022-11-12 03:48:00
【问题描述】:

我正在寻找有关使用定义的过滤器打印 json 数据的帮助。

下面是我的实际输出,但我只想打印下面预期输出中定义的我需要的字段。

{
 "response": {
  "@status": "success",
  "result": {
   "enabled": "yes",
   "group": {
    "mode": "Active-Active",
    "local-info": {
     "url-compat": "Match",
     "app-version": "xxxxxx",
     "gpclient-version": "Not Installed",
     "build-rel": "xxxxx",
     "ha2-port": "dedicated-ha2",
     "av-version": "0",
     "ha2-keep-alive": "split-datapath",
     "url-version": "0000.00.00.000",
     "ha1-backup-ipaddr": "xxxxx",
     "mgmt-hb": "configured",
     "platform-model": "xxxx",
     "av-compat": "Match",
     "vpnclient-compat": "Match",
     "ha1-ipaddr": "xxxxx",
     "ha1-backup-macaddr": "xxxxxx",
     "vpnclient-version": "Not Installed",
     "ha2-macaddr": "xxxxxx",
     "monitor-fail-holdup": "0",
     "priority": "100",
     "preempt-hold": "1",
     "state": "active-primary",
     "version": "1",
    }
   }
  }
 }
}




我在我的代码中使用了什么:

      json_data = json.dumps(output)
  

      print (json_data[0][mode])

期望输出:

{

“模式”:“主动-主动”,

“状态”:“主动主”,

}

...

我得到的输出: {

【问题讨论】:

  • 你的问题不完整。你的输出是什么?
  • 您是否只想打印包含在预期输出中的内容或其他内容,因为您使用了...
  • 什么是输出?它是 Python 字典吗?如果是那么json_data将是一个字符串,在这种情况下,您的打印尝试将失败,因为 Python char (json_data[0]) 不可下标。
  • 我需要过滤实际输出并获得预期输出
  • 您显示的代码不可能发出一个左大括号。请显示您的实际代码

标签: python json


【解决方案1】:

您可以尝试以下方法过滤输出:

import json

output = {
 "response": {
  "@status": "success",
  "result": {
   "enabled": "yes",
   "group": {
    "mode": "Active-Active",
    "local-info": {
     "url-compat": "Match",
     "app-version": "xxxxxx",
     "gpclient-version": "Not Installed",
     "build-rel": "xxxxx",
     "ha2-port": "dedicated-ha2",
     "av-version": "0",
     "ha2-keep-alive": "split-datapath",
     "url-version": "0000.00.00.000",
     "ha1-backup-ipaddr": "xxxxx",
     "mgmt-hb": "configured",
     "platform-model": "xxxx",
     "av-compat": "Match",
     "vpnclient-compat": "Match",
     "ha1-ipaddr": "xxxxx",
     "ha1-backup-macaddr": "xxxxxx",
     "vpnclient-version": "Not Installed",
     "ha2-macaddr": "xxxxxx",
     "monitor-fail-holdup": "0",
     "priority": "100",
     "preempt-hold": "1",
     "state": "active-primary",
     "version": "1",
    }
   }
  }
 }
}


json_data = json.dumps(output, indent=4)
  
print("Mode: "+ output["response"]["result"]["group"]["mode"])
print("State: "+ output["response"]["result"]["group"]["local-info"]["state"])

【讨论】:

    猜你喜欢
    • 2021-05-15
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-08-07
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多