如何从ruby中的JSON数组中检索JSON对象

时间:2016-07-11 09:21:50

标签: ruby json

我有以下JSON响应。在这个JSON中,我有"结果"作为JSON数组。从这个数组我想检索并显示每个实例名称的值和相应的状态。我怎么能这样做?

{
  "oradbInstance" : {
    "oraDBHost" : "",
    "oraDBPort" : "",
    "oraDBSid" : "",
    "oraDBPass" : "",
    "oraDBJdePass" : "",
    "oraDBStatus" : "",
    "oraDBDepComponent" : "",
    "oraSHARED" : false,
    "oraADF" : false,
    "oraOVR" : false,
    "oradbSchema" : {
      "oraPROD" : false,
      "oraPRIST" : false,
      "oraCRP" : false,
      "oraDEV" : false
    },
    "oradbDemoSchema" : {
      "oraPRODDEMO" : false,
      "oraPRISTDEMO" : false,
      "oraCRPDEMO" : false,
      "oraDEVDEMO" : false
    }
  },
  "result" : [ {
    "instanceName" : "ent6327",
    "targetType" : "entserver",
    "status" : "STOPPED"
  }, {
    "instanceName" : "ent790",
    "targetType" : "entserver",
    "status" : "STOPPED"
  }, {
    "instanceName" : "920_ENT_6017",
    "targetType" : "entserver",
    "status" : "RUNNING"
  }, {
    "instanceName" : "ent7943",
    "targetType" : "entserver",
    "status" : "STOPPED"
  }, {
    "instanceName" : "920_JAS_8082",
    "targetType" : "webserver",
    "status" : "RUNNING"
  }, {
    "instanceName" : "ENT6547",
    "targetType" : "entserver",
    "status" : "STOPPED"
  }, {
    "instanceName" : "ent4563",
    "targetType" : "entserver",
    "status" : "STOPPED"
  }, {
    "instanceName" : "ent6021",
    "targetType" : "entserver",
    "status" : "RUNNING"
  }, {
    "instanceName" : "AIS_0005",
    "targetType" : "restserver",
    "status" : "RUNNING"
  }, {
    "instanceName" : "DEN00KNL_DEP_920",
    "targetType" : "depserver",
    "status" : "RUNNING"
  }, {
    "instanceName" : "wls1213",
    "targetType" : "owl_1212",
    "status" : "RUNNING"
  }, {
    "instanceName" : "HTML_8792",
    "targetType" : "webserver",
    "status" : "RUNNING"
  }, {
    "instanceName" : "home",
    "targetType" : "mgmtconsole",
    "status" : "RUNNING"
  }, {
    "instanceName" : "ent6060_Win",
    "targetType" : "entserver",
    "status" : "RUNNING"
  }, {
    "instanceName" : "RTE_0004",
    "targetType" : "rteserver",
    "status" : "RUNNING"
  }, {
    "instanceName" : "ent6363",
    "targetType" : "entserver",
    "status" : "STOPPED"
  } ]
}

任何有用的建议

1 个答案:

答案 0 :(得分:0)

require 'json'
JSON.parse(input)['result'].map do |h|
  [h['instanceName'], h['status']]
end.to_h
#⇒ {
#      "920_ENT_6017" => "RUNNING",
#      "920_JAS_8082" => "RUNNING",
#          "AIS_0005" => "RUNNING",
#  "DEN00KNL_DEP_920" => "RUNNING",
#           "ENT6547" => "STOPPED",
#         "HTML_8792" => "RUNNING",
#          "RTE_0004" => "RUNNING",
#           "ent4563" => "STOPPED",
#           "ent6021" => "RUNNING",
#       "ent6060_Win" => "RUNNING",
#           "ent6327" => "STOPPED",
#           "ent6363" => "STOPPED",
#            "ent790" => "STOPPED",
#           "ent7943" => "STOPPED",
#              "home" => "RUNNING",
#           "wls1213" => "RUNNING"
# }