jq - Cheatsheet
jq - Extract value from JSON
With array index:
cat my.json | jq -r '.[] | .id'Without array index:
cat my.json | jq -r '.config .id'jq - Remove quotes from output value
jq -r $inputjq - 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 ) )'jq - Resources
-
jq
-
GitHub - stedolan/jq - For JSONPath users (opens in a new tab)
A tutorial about how to translate
JSONPathexpressions intojqexpressions
-
Java
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.JSONObjectArtifact:
org.json:json:20210307log.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 }
JSON Lines
-
JSON Lines (opens in a new tab)
-
Features
- For storing structured data that may be processed one record at a time
- Works well with unix-style text processing tools and shell pipelines
- Great format for log files
- Flexible format for streaming messages
- Good for compress lengthy JSON data with lots of lines
- Better replacement for CSV
-
Format
- UTF-8 Encoding
- Each Line is a Valid JSON Value
- Line Terminator is
\n
-
Recommended practices
- JSON Lines files may be saved with the file extension
.jsonl. - MIME type may be
application/jsonl - Stream compressors like
gziporbzip2are recommended for saving space, resulting in.jsonl.gzor.jsonl.bz2files.
- JSON Lines files may be saved with the file extension
-