使用 scala spark 如何仅打印从 HTTP post 调用返回的响应主体值

Using scala spark how to print just the response body value returned from a HTTP post call

我有一个 Flask 应用程序,如果我对它执行 cURL,它 returns 如下:

响应采用 JSON 格式,如下所示:

{"your_field": "hello there buddy"}

我只想获取值“hello there buddy”并打印它。知道怎么做吗?

我有以下代码:

def myExampleFunction  = ( text: String ) => {

  val result = Http("http://localhost:5001/other/post").postData("{\"my_field\":\"" + text + "\"}")
    .header("Content-Type", "application/json")
    .header("Charset", "UTF-8")
    .option(HttpOptions.readTimeout(10000)).asString

  println("result.body is!! : " + result.body)
  result.body

运行 这将打印以下内容:

result.body is!! : {"your_field": "hello there buddy"}

我要实现的是:

result.body is!! : hello there buddy

result.bodystring类型,将字符串数据解析为json数据,提取出需要的字段。

在下面的代码中,我使用了 json4s 库来解析对 json 数据的字符串响应。

  def myExampleFunction  = ( text: String ) => {
    import org.json4s._
    import org.json4s.native.JsonMethods._
    implicit val formats = DefaultFormats

    val result = Http("http://localhost:5001/other/post")
      .postData("{\"my_field\":\"" + text + "\"}")
      .header("Content-Type", "application/json")
      .header("Charset", "UTF-8")
      .option(HttpOptions.readTimeout(10000))
      .asString

    (parse(result.body) \ "your_field").extract[String]
}