0

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)

1 Answer 1

2

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;
}
Sign up to request clarification or add additional context in comments.

7 Comments

Thank You VOX, but if one of the key values are null, I get org.json.JSONException: JSONObject["key_name"] not a string.
Did it happen with the same example? In that case, we could be using different versions of the library.
Yes for null or integer key values I get org.json.JSONException: JSONObject["key"] not a string.
Looks like we had different version of org.json. I updated the initial example and added another one which makes use of the key set that is also provided with the latest version of the library.
Now it's working ;) Thank You VOX. How did you know that this could be a problem with the library version?
|

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.