Search code examples
jsonscalaspray-json

How to parse empty [] using spray.json


I have the following Json:

{
    "my_rule":[
      {
        "labelField": "abc",
        "nodeAttr":[]
      },
      {
        "labelField": "def",
        "nodeAttr":["name","surname"]
      }
    ]
}

I am parsing it in Scala using spray.json:

my_map = parsedJson.map(rule =>
  Map(
    "label" -> rule.labelField,
    "attr" -> rule.nodeAttr(???) // TODO
  )
)

The attr is of type Seq[String].

I don't know how to resolve the case of empty nodeAttr? The goal is to have attr equal to "" and "name,surname".


Solution

  • my_map = parsedJson.map(rule =>
      Map(
        "label" -> rule.labelField,
        "attr" -> (if(rule.nodeAttr.size == 0 ) "" else rule.nodeAttr.mkString(","))
      )
    )