Search code examples
jsonscalahttpsplayframework

How to create a List from a HTTP response string based on certain conditions?


I am trying to parse the result of a HTTPS request in Scala.

The HTTPS response is a String as follows:

{
  "rows":
  [
    {
      "log_forwarding_ip":"",
      "device_name":"AD1",
      "id":"51",
      "mgmt_ip_addr":"192.168.25.150",
      "log_forwarding":"1",
      "isActive":"0"
    },
    {
      "log_forwarding_ip":"192.168.1.1",
      "device_name":"WIN-SRV2019",
      "id":"50",
      "mgmt_ip_addr":"192.168.25.151",
      "log_forwarding":"1",
      "isActive":"1"
    },
    {
      "log_forwarding_ip":"129.168.1.2",
      "device_name":"PA",
      "id":"3",
      "mgmt_ip_addr":"192.168.1.161",
      "log_forwarding":"1",
      "isActive":"1"
    }
  ],
  "status":1
}

I have to create a List of all id's where isActive and log_forwarding are both equal to 1.

So far what I have done is:

object syncTables {
  def main(args: Array[String]): Unit = {
    case class deviceInfo(log_forwarding_ip: String, device_name: String, id: String, 
                          mgmt_ip_addr: String, log_forwarding: String, isActive: String)
    try {
      val r = requests.get("https://192.168.1.253/api/device/deviceinfo.php", verifySslCerts = false)
      if (r.statusCode == 200) {
        val x = r.text
        println(x)
      } else {
        println("Error in API call: "+r.statusCode)
      }
    }
  }
}

Now I'm really confused what to do next to achieve my result.
I'm totally new to JSON, that's why I don't know which JSON library I should use.
I tried using Play Framework but it seems all pretty complicated to me.

Does Scala offer something like Python's json module where this task can be easily done by using dictionaries and lists.

I'm using Scala 2.11.12 and com.lihaoyi.requests.
Any kind of help will be highly appreciated.
Thanks in advance.


Solution

  • Use json4s to parse the JSON string. Let's call your JSON input string json, then you can do something like this

    import org.json4s._
    import org.json4s.jackson.JsonMethods._
    
    case class DeviceInfo(log_forwarding_ip: String, device_name: String, id: String,
                          mgmt_ip_addr: String, log_forwarding: String, isActive: String)
    
    implicit val formats: Formats = DefaultFormats  // Brings in default date formats etc.
    
    val parsedJson = parse(json)
    val deviceInfos = parsedJson match {
      case JObject(head :: _) =>
        head._2
          .extract[List[DeviceInfo]]
          .filter(_.isActive == 1 && _.log_forwarding == 1)
    }
    

    This will output

    val res0: List[DeviceInfo] = List(DeviceInfo("192.168.1.1","WIN-SRV2019","50","192.168.25.151","1","1"),DeviceInfo("129.168.1.2","PA","3","192.168.1.161","1","1"))