[英]Using scala spark how to print just the response body value returned from a HTTP post call
我有一个 flask 应用程序,如果我对其执行 cURL ,它会返回以下内容:
响应采用JSON 格式,如下所示:
{"your_field": "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.body
是string
类型,将字符串数据解析为 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]
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.