使用SCALA play替换嵌套的JSON响应

时间:2014-09-29 09:45:06

标签: json scala

我有以下JSON(myJson)

{  
   "responseHeader":{  },
   "response":{  
      "numFound":5,
      "start":0,
      "docs":[  
         {  
            "product_id":"11",
         },
         {  
            "product_id":"12",
         },
         {  
            "product_id":"13",
         },
         {  
            "product_id":"14",
         },
         {  
            "product_id":"15",
         },
      ]
   },
}

和productToRemove:设置[String] =(11,14)

我想过滤我的JSON并删除Set

中存在的所有产品ID

所以我在我的函数中做了什么()

def function(myJson, productToRemove) : numFound = {
  val docs: List[JsObject] = (myJson \ "response" \ "docs").as[List[JsObject]]
  val newDocs: List[JsObject] = docs.filter(e => (productToRemove.contains((e \ "product_id").as[String])))
}

我想返回更新numFound和docs的newJson,以便结果为

{  
   "responseHeader":{  },
   "response":{  
      "numFound":3,
      "start":0,
      "docs":[  
         {  
            "product_id":"12",
         },
         {  
            "product_id":"13",
         },
         {  
            "product_id":"15",
         },
      ]
   },
}

如何更新这个json?

2 个答案:

答案 0 :(得分:3)

您可以使用文档中描述的Json transformers。你走了:

val productJsonTransformer = (__ \ 'response \ 'docs).json.update(
  __.read[JsValue].map { o =>
    val elems =
      o.as[List[JsObject]].filter { x =>
        val y = x \ "product_id"
        ! productToRemove.contains(y.as[String].toInt)
      }
    Json.toJson(elems)
  })

println(Json.prettyPrint(json.transform(productJsonTransformer).get))

输出:

{
  "responseHeader" : { },
  "response" : {
    "numFound" : 5,
    "start" : 0,
    "docs" : [ {
      "product_id" : "12"
    }, {
      "product_id" : "13"
    }, {
      "product_id" : "15"
    } ]
  }
}

答案 1 :(得分:0)

您可以按照以下方式执行此操作:

def function(myJson: JsValue, productToRemove:List[String]) = {
    val docs: List[JsObject] = (myJson \ "response" \ "docs").as[List[JsObject]]

    // Use filterNot to remove.
    val newDocs: List[JsObject] = docs.filterNot(e => (productToRemove.contains((e \ "product_id").as[String])))

    // extract old response.
    val originalResponse = (myJson \ "response").as[JsObject]

    // update "docs" in old response.
    val newResponse = originalResponse ++ Json.obj("docs" -> newDocs)

    // update "response" in myJson
    myJson.as[JsObject] ++ Json.obj("response" -> newResponse)
}