Search code examples
scalaspray-json

Getting data from json array in scala


I have newly started working on scala. I have following json array:

[
  {
     "id": "1",
    "formatType": "text",
    "value": "bgyufcie huis huids hufhsduhfsl hd"
  },
  {
    "id": "2",
    "formatType": "text size",
    "value": 12
  },
  {
    "id": "3",
    "formatType": "text alignment",
    "value" : "right"
  }
]

I am trying to retrieve json from this array on the basis of id. For example, if id is 2 then I want to retreive following

 {
        "id": "2",
        "formatType": "text size",
        "value": 12
      }

and so on for other id's. I have written a code which compares id and return me json which is as follows.

val getid = jsonString.parseJson match {
      case JsArray(elements) => elements.map(x => if(x.asJsObject().getFields("Id")(0).toString().replace("\"", "") == key) x)
    }

This code works fine when in json array I have only one json. But when I have multiple json with id's as shown above, this code only compares the last record. That is in this case it is only comparing data with id 3. It is not comparing with id 1 and and id 2 and because of which I am not able to get desired results. I tried using for each here but that didn't worked for me. for each prints full data in characters. How can I check all records in my json array and match id and return it?


Solution

  • I agree with the comments about not asking multiple questions, and looking at existing answers (and accepting correct answers!).

    However in this particular case you just need to use find rather than map:

    val getid = jsonString.parseJson match {
      case JsArray(elements) =>
        elements.find(_.asJsObject().getFields("Id")(0).toString().replace("\"", "") == key)
      case _ =>
        None
    }
    

    This will return None if the id is not found or the JSON is not a JsArray, otherwise it will return Some(element)

    More generally, rather than processing the raw JSON objects, I would recommend using a library that converts the whole JSON to Scala objects and then processing those Scala objects.