skip to Main Content

I have a below JSON Array from the below, I want to get commandResponse associated with searched Command.

e.g. lets say I searched command "show version", It should return my commandResponse as 16.0.1.

JSON Array

[{"commandResponse":"","errorMessage":"harddisk crash not applicable.","name":"harddiskcrash","command":"harddiskcrash","status":"NotApplicable"},{"commandResponse":"","errorMessage":"stby-harddisk crash not applicable.","name":"stby-harddiskcrash","command":"stby-harddiskcrash","status":"NotApplicable"},{"commandResponse":"16.0.1","errorMessage":"_showconfigall not applicable.","name":"show_version","command":"show version","status":"NotApplicable"},{"commandResponse":"","errorMessage":"_showpolicy-map not applicable.","name":"_showpolicy-map","command":"_showpolicy-map","status":"NotApplicable"},{"commandResponse":"","errorMessage":"system dirvarlog not applicable.","name":"show version log","command":"show version log","status":"NotApplicable"}]

Note: If you see JSON data show version word is present 2 times, show version & show version log but it should return only show version command data.

I tried to do this using JsonPath:

List<Map<String, Object>> finalDataList = commandsData.read("$[?(@.command == 'Show Version')]");

But it gives me below error:

The method parse(String) is undefined for the type JsonPath

Notes:

  • JSON parser Library – com.googlecode.json-simple

  • commandsData – This is JSON Array

3

Answers


  1. For me, it was easier to map JSONArray to Map<String,Object> and implement functionality there!

    Below is attached my code on kotlin

    fun main() {
    val json =
        "[{"commandResponse":"","errorMessage":"harddisk crash not applicable.","name":"harddiskcrash","command":"harddiskcrash","status":"NotApplicable"},{"commandResponse":"","errorMessage":"stby-harddisk crash not applicable.","name":"stby-harddiskcrash","command":"stby-harddiskcrash","status":"NotApplicable"},{"commandResponse":"16.0.1","errorMessage":"_showconfigall not applicable.","name":"show_version","command":"show version","status":"NotApplicable"},{"commandResponse":"","errorMessage":"_showpolicy-map not applicable.","name":"_showpolicy-map","command":"_showpolicy-map","status":"NotApplicable"},{"commandResponse":"","errorMessage":"system dirvarlog not applicable.","name":"show version log","command":"show version log","status":"NotApplicable"}]"
    val array = JSONParser().parse(json) as JSONArray
    println(findCommandResponseByCommand("show version",array))
    }
    
    fun findCommandResponseByCommand(command: String, jsonArray: JSONArray): String {
        val found = jsonArray
            .map { it as Map<String, Any> }
            .find { it["command"] == command }
        return found?.get("commandResponse") as? String ?: ""
    }
    

    The output is

    16.0.1
    

    Added java code

    public class Test {
    public static void main(String[] args) throws ParseException {
        String json =
                "[{"commandResponse":"","errorMessage":"harddisk crash not applicable.","name":"harddiskcrash","command":"harddiskcrash","status":"NotApplicable"},{"commandResponse":"","errorMessage":"stby-harddisk crash not applicable.","name":"stby-harddiskcrash","command":"stby-harddiskcrash","status":"NotApplicable"},{"commandResponse":"16.0.1","errorMessage":"_showconfigall not applicable.","name":"show_version","command":"show version","status":"NotApplicable"},{"commandResponse":"","errorMessage":"_showpolicy-map not applicable.","name":"_showpolicy-map","command":"_showpolicy-map","status":"NotApplicable"},{"commandResponse":"","errorMessage":"system dirvarlog not applicable.","name":"show version log","command":"show version log","status":"NotApplicable"}]";
        JSONArray array = (JSONArray) new JSONParser().parse(json) ;
        System.out.println(findCommandResponseByCommand("show version",array));
    }
    
    private static String findCommandResponseByCommand(String command, JSONArray jsonArray) {
        Optional result = jsonArray.stream()
                .filter(json ->  ((Map<String, Object>) json).get("command").equals(command))
                .findAny();
        if(result.isPresent()){
            return ((Map<String, Object>) result.get()).get("commandResponse").toString();
        }
        return "";
    }
    }
    
    Login or Signup to reply.
  2. You may consider another library Josson to do the job.

    https://github.com/octomix/josson

    Josson commandsData = Josson.fromJsonString("[{"commandResponse":"","errorMessage":"harddisk crash not applicable.","name":"harddiskcrash","command":"harddiskcrash","status":"NotApplicable"},{"commandResponse":"","errorMessage":"stby-harddisk crash not applicable.","name":"stby-harddiskcrash","command":"stby-harddiskcrash","status":"NotApplicable"},{"commandResponse":"16.0.1","errorMessage":"_showconfigall not applicable.","name":"show_version","command":"show version","status":"NotApplicable"},{"commandResponse":"","errorMessage":"_showpolicy-map not applicable.","name":"_showpolicy-map","command":"_showpolicy-map","status":"NotApplicable"},{"commandResponse":"","errorMessage":"system dirvarlog not applicable.","name":"show version log","command":"show version log","status":"NotApplicable"}]");
    String response = commandsData.getString("[command='show version'].commandResponse");
    System.out.println(response);
    

    Output

    16.0.1
    
    Login or Signup to reply.
  3. To find the required JSON-object in the array, you need to iterate over array elements and check if it contains the target value (like "Show Version"). If the matching object was found, you need to extract the value that corresponds to "commandResponse" from it.

    Here’s how it might be implemented using Stream API (JSONArray is a subtype of ArrayList therefore we can invoke stream() on it):

    @SuppressWarnings("unchecked")
    public static String getResponse(JSONArray array, String search) {
        
        return (String) array.stream()
            .filter(jsonObject -> ((JSONObject) jsonObject).values().stream()
                .anyMatch(s1 -> ((String) s1).equalsIgnoreCase(search))
            )
            .map(jsonObject -> ((JSONObject) jsonObject).get("commandResponse"))
            .findFirst()
            .orElse("given value doesn't exist"); // apply other methods like orElseThrow() depending on your needs
    }
    

    Usage example:

    public static void main(String[] args) throws IOException, ParseException {
        JSONParser parser = new JSONParser();
        String json = "[{"commandResponse":"","errorMessage":"harddisk crash not applicable.","name":"harddiskcrash","command":"harddiskcrash","status":"NotApplicable"},{"commandResponse":"","errorMessage":"stby-harddisk crash not applicable.","name":"stby-harddiskcrash","command":"stby-harddiskcrash","status":"NotApplicable"},{"commandResponse":"16.0.1","errorMessage":"_showconfigall not applicable.","name":"show_version","command":"show version","status":"NotApplicable"},{"commandResponse":"","errorMessage":"_showpolicy-map not applicable.","name":"_showpolicy-map","command":"_showpolicy-map","status":"NotApplicable"},{"commandResponse":"","errorMessage":"system dirvarlog not applicable.","name":"show version log","command":"show version log","status":"NotApplicable"}]";
        JSONArray array = (JSONArray) parser.parse(json);
        System.out.println(getResponse(array, "Show Version"));
    }
    

    Output:

    16.0.1
    

    Note: I would not recommend using org.json.simple for any task apart from very trivial. It is very unflexible, and not type-safe. Its JSONArray extends ArrayList of row type, for that reason type casts pop up all over the place.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search