Syed Junaid Yousuf
Syed Junaid Yousuf

Reputation: 354

Add a Json object to JSON Array using scala play

This is my current json:

{"name":"James",
    "child": {"id":1234,"name":"Ruth",
        "grandchild":{"id":1111,"name":"Peter"}
    }
}

I want to make it like this:

{"name":"James",
    "child": [{"id":1234,"name":"Ruth",
        "grandChild":[{"id":1111,"name":"Peter"}]
     }]
}

Below is the code:

def getParentJSON = {
    Json.obj(
        "name"->"James",
        "child"->getChildJson
    )
}

def getChildJSON = {
    Json.obj(
        "id"->"1234",
        "name"->"Ruth",
        "grandChild"->getGrandChildJson
    )       
}

def getGrandChildJSON = {
    Json.obj(
        "id"->"1111",
        "name"->"Peter"
    )       
}

I tried to use JsArray.append(getParentJSON). But it didn't worked.

Any help will be much appreciated.

Thanks

Upvotes: 3

Views: 921

Answers (1)

danielnixon
danielnixon

Reputation: 4268

Use Json.arr:

def getParentJSON = {
  Json.obj(
    "name" -> "James",
    "child" -> Json.arr(getChildJSON)
  )
}

def getChildJSON = {
  Json.obj(
    "id" -> "1234",
    "name" -> "Ruth",
    "grandChild" -> Json.arr(getGrandChildJSON)
  )
}

Upvotes: 2

Related Questions