Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to ignore case when searching a JSON Object

My sample JSON input is as follows:

"JobName":"Test Job 1",
"events":[
    {   "features":[],
        "InputHiveTable":"uilog_uiclientlogdata",
        "eventColumn":"command",
        "name":"edu.apollogrp.classroom.discussion.client.events.CreateDiscussionEvent"
    },

Consider the field "InputHiveTable", it could be in all uppercase INPUTHIVETABLE, all lowercase inputhivetable, or a mixture of both as it is now.

Currently, I'm reading the field as follows (in Java):

JSONObject jsonObject = (JSONObject) obj;
JSONArray events = (JSONArray) jsonObject.get("events");
String InputHiveTable = (String)event.get("InputHiveTable");

So my question is how do I search for the field "InputHiveTable" while ignoring the case. I'm using JSON Simple libraries.

like image 799
Chaos Avatar asked Aug 05 '13 20:08

Chaos


2 Answers

If you have to perform this case-insensitive lookup many times, I'd just write a method to do that lookup:

public Object getIgnoreCase(JSONObject jobj, String key) {

    Iterator<String> iter = jobj.keySet().iterator();
    while (iter.hasNext()) {
        String key1 = iter.next();
        if (key1.equalsIgnoreCase(key)) {
            return jobj.get(key1);
        }
    }

    return null;

}
like image 72
Chris Gerken Avatar answered Sep 23 '22 10:09

Chris Gerken


Given that case-insensitivity can be achieved with TreeMap (i.e. via String.CASE_INSENSITIVE_ORDER comparator), you can probably do the following:

  1. Implement your own MyJSONObject extending TreeMap where its methods will be just calling static methods of JSONObject with the same signatures and all required interfaces as in JSONObject. In default constructor write super(String.CASE_INSENSITIVE_ORDER)

  2. Implement ContainerFactory interface where createObjectContainer will return new instance of MyJSONObject (and createArrayContainer will just return new JSONArray).

  3. To run it with new container MyContainerFactory:

     StringReader in = new StringReader(yourJSONString);                    
     JSONParser parser = new JSONParser();      
     parser.parse(in, yourContainerFactory)
    
like image 22
Alex P Avatar answered Sep 25 '22 10:09

Alex P