JSON

Cheatsheet

jq - Remove quotes from output value

jq -r $input

jq - Filter by keyword in value

cat my.json | jq -c '.[] | select( ._id | contains(611))'

jq - Filter by exact match

cat my.json | jq -c '.[] | select( ._id == 611 )'

jq - Map output to a new array

cat my.json | jq -c 'map( select( ._id == 611 ) )'

Pretty print JSON representation of an object in Java

  • JSONObject

    // Pretty print an object
    import org.json.JSONObject;
     
    var jsonObject = new JSONObject();
    jsonObject.put("key", "value");
    log.info(jsonObject.toString(4)); // 4 is indentation level
     
    // Pretty print a JSON string
    var jsonString = "{\"key\": \"value\"}";
    log.info(jsonString.toString(4));
  • Jackson

     
    import com.fasterxml.jackson.databind.ObjectMapper;
     
    var objectMapper = new ObjectMapper();
    var jsonObject = objectMapper.createObjectNode();
    jsonObject.put("key", "value");
    log.info(objectMapper.writerWithDefaultPrettyPrinter().writeValueAsString(jsonObject));

Pretty print JSON string in Java

  • org.json.JSONObject

    Artifact: org.json:json:20210307

    log.info("Pretty JSON: {}", new org.json.JSONObject("""
            {"timestamp":"2025-02-06T03:13:19.186+00:00","status":404,"error":"Not Found","path":"/ms-message-hub/v1/ccom/customers/30000/00e805e9-596d-4893-8836-8ab2918f70a9"}
            """).toString(4));

    Output:

    Pretty JSON:
    {
        "path": "/ms-message-hub/v1/ccom/customers/30000/00e805e9-596d-4893-8836-8ab2918f70a9",
        "error": "Not Found",
        "timestamp": "2025-02-06T03:13:19.186+00:00",
        "status": 404
    }

Resources