0

I have a json like this:

{
    "application": "ERP",
    "subject": "Quote 0000005 from TestSG",
    "exportDocumentRequest": {
        "documentDate": "05-02-2020",
        "tenantBillingAddr": null,
        "code": "0000"
      } 
}

I need to replace "code" value i.e "0000" to "1234" I tried following by refering this Building a nested JSONObject

JSONObject requestParams = Utilities.readJSON("MyFile.json");
JSONObject childJSON = new JSONObject();
childJSON.put("code", "1234");
requestParams.put("exportDocumentRequest", childJSON);

but it is giving me output like:

{
    "application": "ERP",
    "subject": "Quote 0000005 from TestSG",
    "exportDocumentRequest": {
        "code": "0000"
      } 
}

It is removing other child fields in "exportDocumentRequest". I need it to be like this with updated "code":

{
    "application": "ERP",
    "subject": "Quote 0000005 from TestSG",
    "exportDocumentRequest": {
        "documentDate": "05-02-2020",
        "tenantBillingAddr": null,
        "code": "1234"
      } 
}
Faisal
  • 159
  • 1
  • 1
  • 13

2 Answers2

1

You should do it with the spread operator.

A spread operator replicates values and you can explicitly update the ones you want. Like i changed code to 5000

let test = {
  "application": "ERP",
  "subject": "Quote 0000005 from TestSG",
  "exportDocumentRequest": {
    "documentDate": "05-02-2020",
    "tenantBillingAddr": null,
    "code": "0000"
  }
}

let updated_test = {
  ...test,
  "exportDocumentRequest": {
    ...test.exportDocumentRequest,
    "code": "5000"
  }
}

console.log(updated_test)
Zunaib Imtiaz
  • 2,849
  • 11
  • 20
  • Hi, what should be the Java equivalent for this? I forgot to update this in the question. I am doing it in java rest assured library. – Faisal Feb 12 '20 at 07:14
  • Follow Up here for JAVA. https://stackoverflow.com/questions/25894559/how-to-edit-modify-nested-jsonobject – Zunaib Imtiaz Feb 12 '20 at 07:19
0

Duplicate of How to edit, modify nested JSONObject

Following worked for me.

requestParams.getJSONObject("exportDocumentRequest").put("code", "1234");
Faisal
  • 159
  • 1
  • 1
  • 13