Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

like image 1000
Syed Junaid Yousuf Avatar asked Feb 16 '26 01:02

Syed Junaid Yousuf


1 Answers

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)
  )
}
like image 128
danielnixon Avatar answered Feb 18 '26 17:02

danielnixon



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!