Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Replace whitespace in JSON keys

Tags:

java

json

parsing

I am thinking of a best solution to replace all the whitespaces in JSON keys with underscore.

{ 
  "Format": "JSON", 
  "TestData": { 
    "Key with Spaces in it": { 
      "And Again": { 
        "Child_Key1": "Financial", 
        "Child_Key2": null 
      }, 
......... 
..... 

I want the above to be converted as shown below:

{ 
  "Format": "JSON", 
  "TestData": { 
    "Key_with_Spaces_in_it": { 
      "And_Again": { 
        "Child_Key1": "Financial", 
        "Child_Key2": null 
      }, 
......... 
..... 

Any suggestions ?

Does any Java library have any predefined function to do this ?

like image 244
gnanagurus Avatar asked Aug 07 '26 17:08

gnanagurus


1 Answers

Replacing Keys

The following code uses Google's JSON parser to extract keys, reformat them, and then create a new JSON object:

public static void main(String[] args) {
    String testJSON = "{\"TestKey\": \"TEST\", \"Test spaces\": { \"child spaces 1\": \"child value 1\", \"child spaces 2\": \"child value 2\" } }";
    Map oldJSONObject = new Gson().fromJson(testJSON, Map.class);
    JsonObject newJSONObject = iterateJSON(oldJSONObject);

    Gson someGson = new Gson();
    String outputJson = someGson.toJson(newJSONObject);
    System.out.println(outputJson);
}

private static JsonObject iterateJSON(Map JSONData) {
    JsonObject newJSONObject = new JsonObject();
    Set jsonKeys = JSONData.keySet();
    Iterator<?> keys = jsonKeys.iterator();
    while(keys.hasNext()) {
        String currentKey = (String) keys.next();
        String newKey = currentKey.replaceAll(" ", "_");
        if (JSONData.get(currentKey) instanceof Map) {
            JsonObject currentValue = iterateJSON((Map) JSONData.get(currentKey));
            newJSONObject.add(currentKey, currentValue);
        } else {
            String currentValue = (String) JSONData.get(currentKey);
            newJSONObject.addProperty(newKey, currentValue);
        }
    }
    return newJSONObject;
}

You can read more about GSON here.

Replacing Values

Depending on how your JSON data is set up, you might need to switch JSONArray with JSONObject.

JSONArrays begin and end with [], while JSONObjects begin and end with {}

In short, these methods will travel over an entire array/object and replace any spaces with underscores. They're recursive, so they will dive into child JSONArrays/JSONObjects.

If the JSON data is encoded as a Java JSONArray, you can do the following:

public static void removeJSONSpaces(JSONArray theJSON) {
    for (int i = 0; while i < theJSON.length(); i++) {
        if (theJSON.get(i) instanceof JSONArray) {
            currentJSONArray = theJSON.getJSONArray(i);
            removeJSONSpaces(currentJSONArray);
        } else {
            currentEntry = theJSON.getString(i);
            fixedEntry = currentEntry.replace(" ", "_");
            currentJSONArray.put(i, fixedEntry);
        }
    }
}

In short, this method will travel over an entire array and replace any spaces with underscores. It's recursive, so it will dive into child JSONArrays.

You can read more about JSONArrays here

If the data is encoded as a JSONObject, you'd want to do something like:

public static void removeJSONSpaces(JSONObject theJSON) {

    jObject = new JSONObject(theJSON.trim());
    Iterator<?> keys = jObject.keys();

    while(keys.hasNext()) {
        String key = (String)keys.next();
        if (jObject.get(key) instanceof JSONObject) {
            removeJSONSpaces(jObject.get(key))
        } else {
            currentEntry = theJSON.getString(i);
            fixedEntry = currentEntry.replace(" ", "_");
            currentJSONArray.put(i, fixedEntry);
        }
    }

}

You can read more about JSONObjects here

like image 95
grill Avatar answered Aug 10 '26 07:08

grill