Remove JSON node from a JSON file in Java

Remove JSON node from a JSON file in Java

Hi, in this blog post, I will cover how to remove given json nodes/keys from a json file. The json data lives in a separate file. For this use case, we are going to use simple json and jackson library.

Here is the JSON file which we are gonna read:

{
  "boolean_key": "--- true\n",
  "empty_string_translation": "",
  "key_with_description": "Check it out! This key has a description! (At least in some formats)",
  "key_with_line-break": "This translations contains\na line-break.",
  "nested": {
    "deeply": {
      "key": "Wow, this key is nested even deeper."
    },
    "key": "This key is nested inside a namespace."
  },
  "null_translation": null,
  "pluralized_key": {
    "one": "Only one pluralization found.",
    "other": "Wow, you have %s pluralization's!",
    "zero": "You have no pluralization."
  },
  "Dog_key": {
    "nest": "Only one pluralization found.",
    "sample_collection": [
      "first item",
      "second item",
      "third item"
    ],
    "Pest": "Only two pluralization found."
  },
  "simple_key": "Just a simple key with a simple message.",
  "unverified_key": "This translation is not yet verified and waits for it. (In some formats we also export this status)"
}

Let's say we want to remove nodes "Dog_key" and "simple_key" in the above JSON file.

Approach:

Actually, there are no nodes in a JSON files. JSON is just a string that needs to be parsed to a real object before you can work with it. So that's the hint for how to parse the JSON first. Once you have parsed, then you can operate on the resulting data object, instead of trying to manipulate the JSON itself.

So, the steps to be followed are:

  • Read the JSON file
  • Parse and convert it into JSONObject using JSONParser's parse() method.
  • Remove the nodes you want.

Using ObjectMapper's writerWithDefaultPrettyPrinter() method you get proper indentation and write that to output file.

The code to remove nodes is shown below:

import com.fasterxml.jackson.databind.ObjectMapper;
import org.json.simple.JSONObject;
import org.json.simple.parser.JSONParser;
import org.json.simple.parser.ParseException;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;
import java.util.stream.Stream;

public class JSONUtil {

    /**
     * Remove given nodes from JSON file
     * @param filePath json file path
     * @param nodeNames nodes to remove in json
     */
    public static void removeNodes(String filePath, String... nodeNames) {
        // read file
        try (FileReader fileReader = new FileReader(filePath)) {
            JSONParser jsonParser = new JSONParser();
            // parse the json file as json object
            JSONObject jsonObject = (JSONObject) jsonParser.parse(fileReader);
            // create stream of nodes you want to remove
            Stream<String> nodeStream = Stream.of(nodeNames);
            // remove the node
            nodeStream.forEach(jsonObject::remove);
            // pretty print for proper indentation
            ObjectMapper objectMapper = new ObjectMapper();
            String jsonObjectPrettified = objectMapper.writerWithDefaultPrettyPrinter().writeValueAsString(jsonObject);
            // write data to output file
            FileWriter fileWriter = new FileWriter(filePath.split("\\.")[0] + "_modified.json");
            fileWriter.write(jsonObjectPrettified);
            fileWriter.close();
        } catch (IOException | ParseException e) {
            e.printStackTrace();
        }
    }

}

Caller:

From main method or where ever you want to call from:

JSONUtil.removeNodes("D:\\data\\JSON_A.json", "Dog_key", "simple_key");

That's it. You have learnt how to remove a node from json data. Thanks for reading!