Tomas
Tomas

Reputation: 81

Java json object replace keys names

I have Json like this:

{
"_id" : ObjectId("5e99f6d16cbddf7dad26557f"),
"channel_id" : 49066,
"timestamp" : NumberLong(1580982302003),
"values" : {
    "some id" : "81151501",
    "some title" : "Some title",
    "some address" : "https://www.some-address.com",
    "new hash" : {
        "some value" : "5",
        "other value" : " 54.10 BRL"
    },
    "wrong values" : "This text have wrong & values & and netx is wrong too & and this &"
},
"null value" : null,
"zero integer" : 0
}

I need to loop through each key and replace spaces with snake_case, for example from other value to other_value

Additionally, I wanted to check every value in the loop by replacing the character & with _, for example:

from This text have wrong & values & and netx is wrong too & and this & to This text have wrong _ values _ and netx is wrong too _ and this _

My json object is made from:

JSONobject jsonObject = new JSONobject(jsonString)

Upvotes: 0

Views: 2203

Answers (1)

vox
vox

Reputation: 440

You could iterate over the keys, normalize the key and recursively continue as long as the value is a JSONObject. If it's not, then you could normalize the value as well. So this would look something like this:

static JSONObject normalize(JSONObject object) throws JSONException {
    JSONObject result = new JSONObject();
    Iterator iterator = object.keys();

    while (iterator.hasNext()) {
        String key = (String) iterator.next();
        String normalizedKey = key.replace(" ", "_");

        Object inner = object.get(key);

        if (inner instanceof JSONObject) {
            result.put(normalizedKey, normalize((JSONObject) inner));
        } else if (inner instanceof String) {
            result.put(normalizedKey, object.getString(key).replace("&", "_"));
        } else {
            result.put(normalizedKey, inner);
        }
    }

    return result;
}

Latest version of the library also provides the ability to obtain a keyset, which would allow for a slightly cleaner looping of the keys:

static JSONObject normalized(JSONObject object) {
    JSONObject result = new JSONObject();

    object.keySet().forEach(key -> {
        String normalizedKey = key.replace(" ", "_");
        Object value = object.get(key);

        if (value instanceof JSONObject) {
            result.put(normalizedKey, normalized((JSONObject) value));
        } else if (value instanceof String) {
            result.put(normalizedKey, ((String) value).replace("&", "_"));
        } else {
            result.put(normalizedKey, value);   
        }
    });     
    return result;
}

Upvotes: 2

Related Questions