0

I'm trying to modify this JSON to remove key values except "url" from an array object of attachment.

Json Path version I'm using: 2.7.0

{
  "fields": {
      "item_name": "mypass\n",
      "id": "nopass cell",
      "Attachment": [
          {
              "id": "attaMKW4RR5misdsD",
              "url": "https://url1.com",
              "filename": "test-nopass.txt",
              "size": 17,
              "type": "text/plain"
          },
          {
              "id": "attHy3s6MBzce7Qoq",
              "url": "https://url2.com",
              "filename": "test-mypass.txt",
              "size": 28,
              "type": "text/plain"
          },
          {
              "id": "atth4oFqzanlk9532",
              "url": "https://url3.com",
              "filename": "test- yourpass .txt",
              "size": 28,
              "type": "text/plain"
          }
      ]
  }
}

here I want to modify this json object to the below code.

{
  "fields": {
      "item_name": "mypass\n",
      "id": "nopass cell",
      "Attachment": [
          {
              "url": "https://url1.com",
          },
          {
              "url": "https://url2.com",
          },
          {
              "url": "https://url3.com",
          }
      ]
  }
}

so how can I achieve this from Jayway JsonPath expression?

JumperBot_
  • 551
  • 1
  • 6
  • 19

1 Answers1

0

I do not think it can be achieved using JsonPath. However, this can be achieved using Jackson.

First, add the following dependency in your pom.xml

<dependency>
   <groupId>com.fasterxml.jackson.core</groupId>
   <artifactId>jackson-databind</artifactId>
   <version>2.13.3</version>
</dependency>

Then you may try the below code. It should work

import java.io.File;
import java.io.IOException;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.node.ObjectNode;
...
public static void removeFieldsFromJson(String json) throws Exception {
        ObjectMapper objectMapper = new ObjectMapper();
        JsonNode jsonNode = objectMapper.readTree(json);
        JsonNode fields = jsonNode.get("fields");
        JsonNode attachments = fields.get("Attachment");
        
        for (JsonNode attachment : attachments) {
            ((ObjectNode) attachment).remove("id");
            ((ObjectNode) attachment).remove("filename");
            ((ObjectNode) attachment).remove("size");
            ((ObjectNode) attachment).remove("type");
        }
        
        objectMapper.writerWithDefaultPrettyPrinter().writeValue(new File("C:\\test\\payload.json"), jsonNode);
    }
Bhanu
  • 53
  • 1
  • 6