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"
      } 
}

2 Answers 2

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)

Sign up to request clarification or add additional context in comments.

2 Comments

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.
0

Duplicate of How to edit, modify nested JSONObject

Following worked for me.

requestParams.getJSONObject("exportDocumentRequest").put("code", "1234");

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.