简体   繁体   English

使用SCALA播放替换嵌套的JSON响应

[英]replacing nested JSON response using SCALA play

I have following JSON (myJson) 我有以下JSON(myJson)

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

and a productToRemove: Set[String] = (11,14) 和productToRemove:Set [String] =(11,14)

I would like to filter my JSON and remove all products Ids which is present in the Set 我想过滤我的JSON并删除Set中存在的所有产品ID

so what i did in my function() 所以我在function()中做了什么

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])))
}

I would like to return newJson which updated numFound and docs so that the result will be 我想返回newJson,它更新了numFound和docs,因此结果将是

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

how to update this json? 如何更新这个JSON?

You can use the Json transformers described in the documentation. 您可以使用文档中描述的Json变压器 Here you go: 干得好:

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))

Output: 输出:

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

You can do it as follows: 您可以按照以下步骤进行操作:

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)
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM