Skip to content
HyperfoilPublic

About

No description, website, or topics provided.

Resources

Stars

5 stars

Watchers

0 watching

Forks

Latest commit

 

History

694 Commits

Folders and files

NameName
Last commit message
Last commit date
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 

Repository files navigation

jjq

High-performance pure Java jq implementation with a bytecode-compiled VM, deferred string parsing, and zero-allocation query execution on large documents.

jjq provides a complete jq filter engine with zero native dependencies, making it portable across all JVM platforms. It executes field access queries in 3 nanoseconds with zero allocation on a 14MB production document, parses 1.5-2.2x faster than Jackson 3, and serializes 1.1-1.8x faster (1.50x on 14MB production data).

Features

  • Full jq syntax — pipes, field access, iteration, array/object construction, string interpolation, reduce, foreach, try-catch, label-break, destructuring bind, function definitions, and more
  • 168 builtin functions (195 name/arity registrations, as of 2026-09-12 — see BuiltinRegistry.java) — comprehensive coverage of jq's standard library including math, string, array, object, path, date/time, and format operations
  • Bytecode VM — fused iteration opcodes, whole-program shape detection, constant folding, peephole optimization, pre-allocated stacks
  • Fast JSON parsing — direct digit accumulation, deferred string values, byte[]-based parsing, field name interning with 64-bit word hashing. 1.7-2.6x faster than Jackson 3 on 1MB inputs; 2.5x faster on 14MB production data
  • On-demand extraction from bytes — JqProgram.apply(byte[]) skips unparsed subtrees and materializes only matched values: .user on a 14MB upload in ~14 ns with 32 B of allocation (vs ~10 ms and 12 MB for a full parse). Strict variant (applyStrict) validates the whole document with identical semantics
  • Zero-allocation queries — field access, deep field chains, keys, and length on pre-parsed documents produce zero garbage
  • Thread-safe — compiled programs are immutable and can be shared across threads
  • YAML support — jjq-yaml parses and emits YAML with a dependency-free native parser, with optional jjq-mapper integration for YAML → POJO mapping via the YamlMapper facade
  • JSON Schema validation — jjq-schema compiles 2020-12/draft-07 schemas once into an immutable graph shared across documents and threads (boolean plus reporting execution)
  • Structural diff — jjq-core computes strict RFC 6902 patches over JqValue (plus apply, lenient comparison reports, and jq-style rendering)
  • Record and POJO data binding — jjq-mapper maps JqValue to/from Java types with @JqName, @JqAccess, @JqVisibility, @JqInclude, @JqNaming, @JqConverter, @JqAdapter, @JqEnum, and Jackson/JSON-B annotation bridges
  • Jakarta EE integration — jjq-jakarta module provides Hibernate persistence (BYTEA + JSONB), JPA AttributeConverter, JAX-RS body/param providers, and JSON-B serializers
  • Jackson Module — jjq-jackson (Jackson 3, tools.jackson.*) includes JqValueModule for native JqValue serialization in POJOs via JsonMapper
  • Jackson migration compat — path(), isMissingNode(), asText(default) aliases; nested builders (putObject/putArray); annotation bridges for transparent adoption
  • Multiple JSON adapters — Jackson, fastjson2, and byte[] adapters with lazy zero-copy conversion
  • Java 21+ — leverages sealed classes, records, and pattern matching

Modules

Module Description
jjq-core Lexer, parser, AST, bytecode VM, builtins (zero external dependencies)
jjq-jackson Jackson 3 integration (tools.jackson.*) — JsonNode ↔ JqValue conversion, JqValueModule for native POJO serialization
jjq-fastjson2 fastjson2 adapter with lazy conversion and streaming APIs
jjq-jakarta Hibernate persistence, JPA AttributeConverter, JAX-RS providers, ParamConverter, and JSON-B serializers
jjq-mapper Record and POJO data binding — map JqValue to/from Java types with @JqField, @JqName, @JqAccess, @JqVisibility, @JqInclude, @JqNaming, @JqConverter, @JqAdapter, @JqEnum
jjq-mapper-processor Compile-time annotation processor for jjq-mapper — generates optimized mappings (~28x faster than Jackson 3 on pre-parsed records)
jjq-mapper-jackson Bridges Jackson annotations (@JsonProperty, @JsonIgnore, @JsonInclude) into jjq-mapper — one bridge for Jackson 2.x and 3.x
jjq-mapper-jsonb Bridges JSON-B annotations (@JsonbProperty, @JsonbTransient, @JsonbNillable) into jjq-mapper
jjq-yaml Dependency-free native YAML parsing into JqValue trees plus block-style emission — enables jq queries over YAML documents
jjq-xml Dependency-free JDK-StAX XML parsing into JqValue trees plus emission — enables jq queries over XML documents
jjq-schema Zero-dependency JSON Schema validation (2020-12 subset, draft-07 compatible) — compile once, validate across documents and threads
jjq-jsonata Compile-time JSONata-to-jq transpiler — 468/1219 conformance tests passing
jjq-jsonpath SQL/JSON path to jq converter with lax/strict mode support — 300/558 conformance (error agreement included)
jjq-cli Command-line interface (zero dependencies, GraalVM native-image ready)
jjq-vector Optional SIMD kernels (JDK 27+) — Vector API container skipper, single-pass strict validator, string validator, and escape copier, ServiceLoader-discovered, scalar fallbacks always present
jjq-test-suite 466 conformance tests + 525 upstream jq tests (96.0% passing)
jjq-benchmark JMH benchmarks vs Jackson 3.2.3: parsing, serialization, mapper, allocation profiling

Quick Start

Maven

<dependency>
    <groupId>io.hyperfoil.tools</groupId>
    <artifactId>jjq-core</artifactId>
    <version>0.1.13-SNAPSHOT</version>
</dependency>

<!-- For Jackson integration -->
<dependency>
    <groupId>io.hyperfoil.tools</groupId>
    <artifactId>jjq-jackson</artifactId>
    <version>0.1.13-SNAPSHOT</version>
</dependency>

<!-- For Hibernate/JAX-RS integration -->
<dependency>
    <groupId>io.hyperfoil.tools</groupId>
    <artifactId>jjq-jakarta</artifactId>
    <version>0.1.13-SNAPSHOT</version>
</dependency>

<!-- For JSONata support -->
<dependency>
    <groupId>io.hyperfoil.tools</groupId>
    <artifactId>jjq-jsonata</artifactId>
    <version>0.1.13-SNAPSHOT</version>
</dependency>

Core API (zero dependencies)

import io.hyperfoil.tools.jjq.JqProgram;
import io.hyperfoil.tools.jjq.value.JqValues;
import io.hyperfoil.tools.jjq.value.JqValue;

// Compile once, apply many times (thread-safe)
JqProgram program = JqProgram.compile(".users[] | {name, email}");

JqValue input = JqValues.parse("""
    {"users": [
        {"name": "Alice", "email": "alice@example.com", "age": 30},
        {"name": "Bob", "email": "bob@example.com", "age": 25}
    ]}
    """);

List<JqValue> results = program.applyAll(input);
results.forEach(r -> System.out.println(r.toJsonString()));
// {"name":"Alice","email":"alice@example.com"}
// {"name":"Bob","email":"bob@example.com"}

Parse from byte[] (fastest path)

// Parse directly from bytes — no intermediate String allocation
byte[] jsonBytes = Files.readAllBytes(Path.of("data.json"));
JqValue data = JqValues.parse(jsonBytes);

Serialize to byte[] (zero-copy path)

// Serialize directly to UTF-8 bytes — no intermediate String allocation
byte[] output = JqValues.serializeToBytes(data);

// Also works with OutputStream (uses the byte path internally)
JqValues.serializeTo(data, outputStream);

For documents parsed from byte[], deferred string values are copied as raw bytes without constructing Java Strings or re-encoding UTF-8. This makes the parse(byte[]) -> serializeToBytes() round-trip optimal for pass-through workloads like database persistence and message queues.

Reusable serialization buffers

Both serialization paths reuse thread-local buffers. For tight loops, acquire the buffer directly to avoid per-call setup:

// String path — reuse the thread-local StringBuilder
StringBuilder sb = JqValues.acquireSerializerBuffer();
data.appendTo(sb);
String json = JqValues.releaseSerializerBuffer(sb);

// Byte path — reuse the thread-local BytOutput (public growable byte buffer)
BytOutput out = JqValues.acquireByteBuffer();
data.appendToBytes(out);
byte[] bytes = JqValues.releaseByteBuffer(out);

// Zero-copy stream write — no intermediate array
BytOutput out2 = JqValues.acquireByteBuffer();
data.appendToBytes(out2);
JqValues.writeByteBuffer(out2, outputStream);

Parse variants

JqValues.parse(jsonString);              // String input (delegates to byte[] path)
JqValues.parse(bytes);                   // byte[] input (fastest)
JqValues.parse(bytes, offset, length);   // byte[] slice
JqValues.parse(inputStream);             // InputStream (throws IOException)
JqValues.parseStrict(jsonString);        // Rejects trailing content (for fromjson)
JqValues.parseStrict(jsonString,         // + depth limit, BOM/NUL policy
    ParseOptions.defaults().withMaxDepth(128));
JqValues.parseStrict(bytes, offset,      // strict byte[] slice
    length, ParseOptions.defaults());
JqValues.parseAll(jsonString);           // JSONL / multi-document streams

Navigate and extract values

For repeated queries, always use JqProgram.compile() -- it compiles once and executes in nanoseconds:

// Compile once at startup (thread-safe, reusable)
JqProgram getName = JqProgram.compile(".user");
JqProgram getResults = JqProgram.compile(".autobench_workload.data[0].results");

// Apply many times (3 ns per field access, zero allocation)
JqValue user = getName.apply(data);
JqValue results = getResults.apply(data);

For programmatic navigation (traversing results, iterating dynamic field names), use the null-safe convenience methods:

// Null-safe chaining -- returns JqNull.NULL for missing paths or type mismatches
JqValue results = data.getField("workload").getField("data").getElement(0).getField("results");

// JSON Pointer navigation (RFC 6901)
JqValue results = data.at("/workload/data/0/results");

// Safe value extraction with defaults
String name = data.getField("user").asString("unknown");
long count = data.getField("count").asLong(0);
int page = data.getField("page").asInt(1);
double score = data.getField("score").asDouble(0.0);

// Coercing extractors -- extract numbers from JqNumber or numeric strings
Double value = data.getField("metric").tryDouble();   // null if not numeric
Long id = data.getField("id").tryLong();               // null if not parseable
Integer port = data.getField("port").tryInt();          // null if not parseable

// Fail-fast access -- throws JqTypeError if missing
JqValue required = data.required("user");              // throws if missing
JqValue element = data.required(0);                    // throws if out of bounds

// Type checks
data.isNull();              data.isString();
data.isNumber();            data.isBoolean();
data.isArray();             data.isObject();
data.isIntegralNumber();    data.isFloatingPointNumber();

// Check existence
if (data.has("user") && !data.getField("items").isEmpty()) {
    // ...
}

// Iterate arrays directly (JqArray implements Iterable<JqValue>)
JqArray items = (JqArray) data.getField("items");
for (JqValue item : items) {
    System.out.println(item.getField("name").asText());
}

// Stream support
List<String> names = items.stream()
    .filter(item -> item.getField("active").asBoolean(false))
    .map(item -> item.getField("name").asText())
    .toList();

// Object accessors — forEach avoids Map.Entry allocation for array-backed objects
JqObject config = (JqObject) data.getField("config");
config.forEach((key, val) -> System.out.println(key + "=" + val));
for (String key : config.keys()) { /* ... */ }
for (var entry : config.entries()) { /* ... */ }

// Indexed access — O(1) for array-backed objects, no Iterator allocation
int n = config.size();
for (int i = 0; i < n; i++) {
    String key = config.keyAt(i);
    JqValue val = config.valueAt(i);
}

// Optional-based lookup — distinguishes absent keys from explicit nulls
Optional<JqValue> maybe = config.tryGet("user");  // empty if absent
Optional<JqValue> present = config.tryGet("nick"); // of(JqNull.NULL) if {"nick": null}

On-demand extraction from bytes

For sparse queries over large documents, apply(byte[]) extracts matched values directly from raw JSON bytes — skipped subtrees are never parsed into JqValue trees:

JqProgram extractUser = JqProgram.compile(".user");
JqProgram extractMetric = JqProgram.compile(
    "[.autobench_workload.data[0].pcp_time_series[] | .[\"mem.util.used\"]]");

// 14MB document: .user in ~14 ns with 32 B allocation
// (eager parse + apply: ~10 ms and 12 MB of tree)
JqValue user = extractUser.apply(jsonBytes);
JqValue metric = extractMetric.apply(jsonBytes);   // ~0.3 ms, 21.7 KB

// Region overload for buffer slices
JqValue user2 = extractUser.apply(jsonBytes, offset, length);

Supported shapes (recognized at compile time, shared by both apply(byte[]) and apply(JqDocument)): field access, chained field/index paths (.a.b[0].c), array field collection ([.items[] | .field] / .items | map(.field), multi-step tails), flat object projections ({a, b} / .cfg | {a, b}), array collect-projections ([.items[] | {a, b}] / .items | map({a, b})), filtered collections ([.items[] | select(<pred>) | <tail>] and map(select(<pred>) | <tail>) across all six comparisons plus truthiness select(.flag) / select(.flag | not)), streaming array reductions (add, min, max over arrays, map(...), or filtered streams, plus [... | select(...)] | length without allocating an intermediate array), and builtin tails (length, keys, keys_unsorted, type, has("k"), has(i)). Anything else — plus escaped wire keys or malformed input — falls back transparently to apply(JqValues.parse(json)), so results and errors always match the eager path. Lenient semantics: extraction stops once the matches are found (trailing bytes are not validated).

Strict variant — applyStrict(byte[], ParseOptions) validates the whole document and behaves exactly like apply(JqValues.parseStrict(json, options)), including thrown errors. The skip-and-materialize fast path engages when the duplicate-key policy is TRUST_UNIQUE (the caller's uniqueness guarantee):

ParseOptions options = ParseOptions.defaults()
    .withDuplicatePolicy(ParseOptions.DuplicatePolicy.TRUST_UNIQUE);

// 14MB document, whole-document strict validation included:
// ~4.7-5.5 ms scalar, ~1.4-1.7 ms with jjq-vector
// (eager strict parse + apply: ~10.3 ms and 12 MB of tree)
JqValue user = extractUser.applyStrict(jsonBytes, options);

With the default REJECT policy (or KEEP_LAST), applyStrict always composes a full strict parse — duplicate detection requires touching every key.

Optional SIMD acceleration — adding the jjq-vector module (JDK 27+) and the --add-modules jdk.incubator.vector JVM flag accelerates subtree skipping (5.9–8.2×), single-pass strict validation (~3× on compact docs, ~2× on numeric telemetry), JqDocument tape parsing (~1.7–1.8× over scalar), and long-string escape scanning with zero code changes (see jjq-vector/README.md). Without it, everything runs on the scalar SWAR path.

Multi-query tape parsing (JqDocument)

When running many queries against one document (or caching parsed payloads in memory without GC reference-graph overhead), JqDocument parses UTF-8 JSON into a flat primitive long[] tape with zero per-node Java object allocations:

// Parse once into a flat long[] tape (zero-copy over jsonBytes)
JqDocument doc = JqValues.parseDocument(jsonBytes);
// Or strict with full ParseOptions (UTF-8, BOM, NUL, maxDepth, DuplicatePolicy)
JqDocument strictDoc = JqValues.parseDocumentStrict(jsonBytes, options);

// Query directly on the tape with O(1) subtree skips & container length
JqValue user = JqProgram.compile(".user").apply(doc);
JqValue len = JqProgram.compile(".items | length").apply(doc);

// Direct tape-to-bytes serialization or full tree materialization when needed
byte[] compact = doc.toJsonBytes();
JqValue tree = doc.toJqValue();

Choosing the right parsing path:

  • 1 sparse query per payload → JqProgram.apply(byte[]) / applyStrict(byte[], ParseOptions) (no parse tree, near-zero allocation)
  • Many queries or cached read-only documents → JqDocument (JqValues.parseDocument* + JqProgram.apply(JqDocument)): on the 14 MB production upload, parsing + 10 queries runs in 4.9 ms pure scalar (2.8–2.9 ms with jjq-vector) vs 9.8 ms eager tree and 7.1 ms repeated scalar apply(byte[]), with 1 primitive array and 0 GC object references
  • Large NDJSON streams or huge top-level JSON arrays (InputStream) → JsonStreamReader (JqValues.stream* / streamArray*) or JqProgram.applyStream* / applyArrayStream* (bounded O(single-record) memory, no readAllBytes())
  • Tree mutation, programmatic building, or heavy general jq transforms → JqValue (JqValues.parse / parseStrict)

Streaming from InputStream (NDJSON & large arrays)

For large NDJSON / concatenated JSON streams or huge top-level JSON arrays where buffering the full stream via readAllBytes() isn't acceptable, JsonStreamReader frames records incrementally over a reusable 64 KB sliding buffer (growing only if an individual record exceeds buffer size):

// Stream NDJSON or concatenated JSON values as JqValue or JqDocument
try (JsonStreamReader reader = JqValues.streamStrict(inputStream, options)) {
    JqValue record;
    while ((record = reader.nextValue()) != null) { /* ... */ }
}

// Stream elements of a single huge top-level JSON array ([elem0, elem1, ...])
try (JsonStreamReader reader = JqValues.streamArray(inputStream)) {
    reader.documents().forEach(doc -> { /* query doc on tape */ });
}

// Apply a compiled JqProgram directly over a stream (uses on-demand
// BytePathPlan skipping per record without building full parse trees)
JqProgram.compile(".name").applyStream(ndjsonStream, out::add);
JqProgram.compile(".id").applyArrayStream(arrayStream, out::add);

// Single-document convenience (reads all bytes, then parses)
try (InputStream in = connection.getInputStream()) {
    JqValue data = JqValues.parse(in);
}

Pretty-print JSON

// Compact (default)
String compact = value.toJsonString();  // {"name":"Alice","age":30}

// Pretty-printed with 2-space indentation
String pretty = JqValues.toPrettyJsonString(value);
// {
//   "name": "Alice",
//   "age": 30
// }

// Jackson INDENT_OUTPUT spacing + terminal-safe escaping
String jacksonStyle = JqValues.toPrettyJsonString(value, PrettyPrintOptions.JACKSON);
String strict = JqValues.toPrettyJsonString(value, new PrettyPrintOptions(
    PrettyPrintOptions.Separator.SPACED,
    PrettyPrintOptions.ArrayStyle.FLOW,
    PrettyPrintOptions.Escaping.STRICT));  // DEL/C1/bidi controls -> \uXXXX

Convert between JqValue and Java types

Recursive conversion for integrating with libraries that operate on Map/List/primitives (JSONata engines, GraalVM polyglot, JDBC, template engines):

// Java → JqValue (null → JqNull.NULL, Map → JqObject, List → JqArray, etc.)
Map<String, Object> javaMap = Map.of("name", "Alice", "scores", List.of(1, 2, 3));
JqValue value = JqValues.fromJavaObject(javaMap);

// JqValue → Java (JqNull → null, JqObject → LinkedHashMap, JqArray → ArrayList, etc.)
Object javaObj = value.toJavaObject();

// JqNumber.of(Number) — accepts any Number subtype (Integer, Long, Double, Float, BigDecimal, etc.)
JqNumber n = JqNumber.of(someNumber);  // auto-promotes integral types to long-backed

Type structure (schema inference)

Compute a type skeleton from a JSON document — replaces leaf values with their type names while preserving the object/array structure. Useful for schema inference, data profiling, and structural comparison:

JqValue input = JqValues.parse("""
    {"name": "Alice", "age": 30, "scores": [95, 87.5]}
    """);

JqValue schema = JqValues.typeStructure(input);
// {"name":"string","age":"integer","scores":["number"]}

Type mapping: null -> "null", boolean -> "boolean", integral number -> "integer", floating-point -> "number", string -> "string". Arrays merge element schemas into a single representative.

Merge schemas from multiple documents to build a unified type structure:

JqValue doc1 = JqValues.parse("{\"value\": 42}");
JqValue doc2 = JqValues.parse("{\"value\": 3.14, \"extra\": true}");

JqValue merged = JqValues.mergeTypeStructures(
    JqValues.typeStructure(doc1),
    JqValues.typeStructure(doc2));
// {"value":"number","extra":"boolean"}
// "integer" + "number" promoted to "number"; keys unioned

Build JSON values

import io.hyperfoil.tools.jjq.value.*;

// Object builder with type-safe convenience methods
JqObject result = JqObject.builder()
    .put("name", "Alice")
    .put("age", 30)
    .put("score", 95.5)
    .put("active", true)
    .put("data", someJqValue)   // null is treated as JqNull.NULL
    .build();

// Pre-sized builder avoids array growth for known field counts
JqObject sized = JqObject.builder(8).put("a", 1).build();

// putUnchecked skips the duplicate-key scan when keys are unique by
// construction (also coerces null to JqNull.NULL)
JqObject fast = JqObject.builder(3)
    .putUnchecked("a", 1L)
    .putUnchecked("b", "x")
    .putUnchecked("c", true)
    .build();

// Array builder
JqArray items = JqArray.arrayBuilder()
    .add("first")
    .add("second")
    .add(42)
    .build();

// Quick object construction with auto-wrapped values (String, Number, Boolean, null)
JqObject block = JqObject.ofEntries(
    "type", "header",
    "count", 42,
    "active", true,
    "nested", JqObject.ofEntries("key", "value")
);

// Copy-on-write modification (immutable — returns new instances)
JqObject updated = result.with("status", JqString.of("verified"));
JqObject merged = result.merge(otherObject);
JqObject deepMerged = result.deepMerge(otherObject);  // recursive merge for nested objects
JqObject without = result.without("age");

Jackson integration

Register JqValueModule on an ObjectMapper to natively serialize/deserialize JqValue fields in POJOs — no manual conversion needed:

import com.fasterxml.jackson.databind.ObjectMapper;
import io.hyperfoil.tools.jjq.jackson.JqValueModule;

ObjectMapper mapper = new ObjectMapper();
mapper.registerModule(new JqValueModule());

// POJOs with JqValue fields work automatically
record Config(String name, JqValue settings) {}
String json = mapper.writeValueAsString(new Config("prod", myJqValue));
Config restored = mapper.readValue(json, Config.class);

Use JacksonJqEngine to apply jq filters to Jackson JsonNode trees:

import io.hyperfoil.tools.jjq.jackson.JacksonJqEngine;

JacksonJqEngine engine = new JacksonJqEngine(mapper);
JqProgram program = engine.compile(".users[] | {name, email}");
JsonNode input = mapper.readTree(requestBody);
List<JsonNode> results = engine.apply(program, input);

See the jjq-jackson README for full details on lazy conversion, Spring Boot, and Quarkus integration.

JSONata support (jjq-jsonata)

Run JSONata expressions through jjq's optimized bytecode VM. The transpiler converts JSONata to jq at compile time — zero runtime overhead:

import io.hyperfoil.tools.jjq.jsonata.JsonataCompiler;

// Compile JSONata to jq (one-time cost, ~microseconds)
JqProgram program = JsonataCompiler.compile("$sum(orders.price)");

// Execute through jjq's bytecode VM — same performance as native jq
JqValue result = program.apply(data);

Supports navigation, operators, predicates, 35+ built-in functions, and implicit array mapping. Lambdas ($map/$filter/$reduce), variable binding ($x :=), block expressions, regex literals, ** recursive descent, and the ~> pipe operator are not yet supported (throw JsonataException). See the jjq-jsonata README for full details and conformance status.

Jakarta EE integration (jjq-jakarta)

Use JqValue directly as a Hibernate entity field type, in REST endpoints, and with JSON-B.

Hibernate persistence — BYTEA (recommended) or JSONB columns:

@Entity
public class MyEntity {
    // Option 1: BYTEA — zero-copy byte[] I/O (recommended)
    @JqValueColumn
    @Column(columnDefinition = "BYTEA")
    public JqValue data;

    // Option 2: Portable JPA — works with any JPA provider
    @Convert(converter = JqValueConverter.class)
    @Column(columnDefinition = "TEXT")
    public JqValue metadata;
}

JAX-RS providers — auto-discovered via @Provider:

@POST @Path("/upload")
public Response upload(JqValue data) {           // MessageBodyReader
    service.store(data);
    return Response.ok().build();
}

@GET @Path("/{id}")
public JqValue get(@PathParam("id") long id) {   // MessageBodyWriter
    return service.load(id);
}

@GET @Path("/search")
public Response search(@QueryParam("filter") JqValue filter) {  // ParamConverter
    return Response.ok(service.search(filter)).build();
}

JSON-B support — for environments using JSON-B instead of Jackson:

JsonbConfig config = new JsonbConfig()
    .withSerializers(new JqValueJsonbSerializer())
    .withDeserializers(new JqValueJsonbDeserializer());
Jsonb jsonb = JsonbBuilder.create(config);

See the jjq-jakarta README for full setup details, including Quarkus and Spring Boot configuration.

With variables

import io.hyperfoil.tools.jjq.evaluator.Environment;

JqProgram program = JqProgram.compile(".[] | select(.name == $target)");
Environment env = new Environment();
env.setVariable("target", JqString.of("Alice"));

List<JqValue> results = program.applyAll(input, env);

Processing multiple inputs (JSONL)

List<JqValue> inputs = JqValues.parseAll("""
    {"name":"Alice","age":30}
    {"name":"Bob","age":25}
    """);

JqProgram program = JqProgram.compile(".name");
List<JqValue> names = program.applyAll(inputs);

Program introspection

// Detect if a program needs --null-input mode (uses input/inputs builtins)
JqProgram program = JqProgram.compile("[inputs | .name]");
if (program.usesNullInput()) {
    results = program.applyNullInput(sourceValues);
} else {
    results = program.applyAll(input);
}

// Check if a program references any specific builtin
program.referencesBuiltin("inputs");  // true
program.referencesBuiltin("length");  // false

CLI Usage

jjq [OPTIONS] FILTER [FILE...]

Options

Option Description
-c, --compact-output Compact output (no pretty-printing)
-r, --raw-output Output raw strings (no JSON quotes)
-R, --raw-input Read each input line as a string
-s, --slurp Read all inputs into an array
-n, --null-input Use null as input
-e, --exit-status Set exit status based on output
-S, --sort-keys Sort object keys in output
-j, --join-output Don't print newlines between outputs
-f, --from-file FILE Read filter from file
--arg NAME VALUE Set $NAME to string VALUE
--argjson NAME JSON Set $NAME to parsed JSON value
--tab Use tab for indentation
--indent N Use N spaces for indentation (default: 2)
--input-format FMT Input format: json or yaml (default: json)
--output-format FMT Output format: json or yaml (default: json)

YAML output is block-style with --- between documents. -c/--tab/-j/-S apply to JSON output only; --indent N sets the YAML indent width (1-10).

Examples

# Field access
echo '{"name":"Alice","age":30}' | jjq '.name'
# "Alice"

# Filter and transform
echo '[1,2,3,4,5]' | jjq '[.[] | select(. > 2) | . * 10]'
# [30,40,50]

# Object construction
echo '{"first":"Alice","last":"Smith","age":30}' | jjq '{full: (.first + " " + .last), age}'
# {"full":"Alice Smith","age":30}

# Reduce
echo '[1,2,3,4,5]' | jjq 'reduce .[] as $x (0; . + $x)'
# 15

# Process JSONL (one JSON value per line)
printf '{"name":"Alice"}\n{"name":"Bob"}\n' | jjq '.name'
# "Alice"
# "Bob"

# Query YAML with the same filters (jq queries over YAML, not yq-compatible flags)
printf 'spec:\n  replicas: 2\n' | jjq --input-format yaml '.spec.replicas'
# 2

# Update YAML and write it back (--output-format yaml separates documents with ---)
printf 'spec:\n  replicas: 2\n' | jjq --input-format yaml --output-format yaml '.spec.replicas = 3'
# spec:
#   replicas: 3

# Convert JSON to YAML
echo '{"spec":{"replicas":2}}' | jjq --output-format yaml '.'
# spec:
#   replicas: 2

Performance

JSON Parsing: jjq vs Jackson 3

Parsing throughput on byte[] inputs (ms/op, lower is better). Measured with JMH, 3 forks, 5+5 iterations, JDK 27 Temurin. Jackson version: 3.2.3.

Input jjq (byte[]) Jackson 3 (byte[]) jjq speedup
flat 1MB 1.80 ms 3.03 ms 1.7x
strings 1MB 0.78 ms 2.00 ms 2.6x
numbers 1MB 1.84 ms 3.58 ms 1.9x
nested 1MB 1.50 ms 2.84 ms 1.9x
Production 14MB 9.66 ms 23.69 ms 2.5x

jjq's byte[] parser is 1.7-2.6x faster than Jackson 3 across all input types. The biggest win is on string-heavy JSON (2.6x) where deferred string construction avoids allocating Java Strings for untouched values. Field name interning with 64-bit word hashing enables zero-allocation queries on the parsed document. Strict parsing (full-document UTF-8 and grammar validation) parses the same 14MB file in 14.4 ms.

On-demand extraction from bytes

JqProgram.apply(byte[]) on the 14MB production upload (351K nodes) versus eager parse(byte[]) + apply. JMH, 3 forks, JDK 27 Temurin:

Query Eager parse + apply apply(byte[]) Speedup Allocation
.user 10.6 ms 0.014 us 734,000x 12.08 MB → 32 B
{user, uuid, run_id, start_time, end_time} 10.7 ms 0.14 us 77,000x 12.08 MB → 240 B
.rhivos_config | {build, model, kernel, architecture} 10.4 ms 22 us 465x 12.08 MB → 209 B
.autobench_workload.data[0].results.autobench_results 10.2 ms 112 us 91x 12.08 MB → 3.7 KB
[.stressng_workload.data[] | .sample_uuid] 10.2 ms 109 us 93x 12.08 MB → 342 B
[.pcp_time_series[] | .["mem.util.used"]] (502 entries) 10.1 ms 286 us 35x 12.08 MB → 21.7 KB

Skipped subtrees are never parsed into JqValue trees — only the matched values materialize. The same queries through applyStrict(bytes, TRUST_UNIQUE) (whole-document strict validation included) run in ~4.7–5.5 ms on the scalar path and ~1.4–1.7 ms with jjq-vector (6–7× over eager strict parse + apply) with the same near-zero allocation. Additional on-demand shapes (length, keys, type, has("k"), [.arr[] | {a, b}], and [.arr[] | select(...) | ...]) achieve 10–528× speedups over eager parse + apply on the same 14 MB document.

Production Query Execution on 14MB Document

Query execution on a pre-parsed 14MB production upload (351K nodes, 3,668 objects). Times via JqProgram.apply() — the library API path including compiled program dispatch. JMH, 3 forks, JDK 27 Temurin:

Query Expression Time Allocation
Top-level field .user 1.6 ns 0 B
Deep field (4 levels) .autobench_workload.data[0].results 46 ns 0 B
Deep field (5 levels) .autobench_workload.data[0].results.autobench_results 56 ns 0 B
Keys (127-key object) .data[0].pcp_time_series[0] | keys 62 ns 0 B
Array length .data[0].pcp_time_series | length 52 ns 0 B
PCP entry (127-key object) .data[0].pcp_time_series[0] 55 ns 0 B
Object construction {user, uuid, run_id, start_time, end_time} 81 ns 112 B
Config extract .rhivos_config | {build, model, kernel, architecture} 85 ns 112 B
Iterate + extract [.stressng_workload.data[] | .sample_uuid] 51 ns 64 B
Extract metric (502 entries) [.pcp_time_series[] | .["mem.util.used"]] 1.5 us 2.1 KB

Six of the ten production benchmarks above achieve zero allocation per query — the result comes directly from the pre-parsed document with no object creation. Single field access bypasses the VM entirely via inlined fast path detection.

Record Data Binding: jjq-mapper vs Jackson 3

Deserialization from pre-parsed tree to Java records (ns/op, lower is better). JMH, 3 forks, 5+5 iterations, JDK 25.0.4 Temurin.

Record type jjq generated jjq reflection Jackson 3 gen vs Jackson
simple (5 fields) 6 ns 39 ns 223 ns 34.9x
nested (record in record) 14 ns 53 ns 368 ns 26.6x

End-to-end deserialization from byte[] to Java records:

Record type jjq (fromBytes) Jackson 3 (fromBytes) jjq speedup
simple 158 ns 363 ns 2.3x
nested 205 ns 468 ns 2.3x
list 477 ns 954 ns 2.0x

The compile-time annotation processor (jjq-mapper-processor) generates _JqMapping classes that map fields via direct constructor and accessor calls, avoiding reflection and lambda overhead. The generated mappings maintain a 25-35x advantage over Jackson 3 on small pre-parsed records (34.9x simple, 26.6x nested, JMH 3 forks, JDK 25.0.4 Temurin, Jackson 3.2.3), narrowing to ~2x at 20 fields. Even the reflection-based mapper (no annotation processor) is ~6x faster than Jackson 3 thanks to pre-cached method handles, single-lookup tryGet, and positional field matching.

JSON Serialization: jjq vs Jackson 3

Serialization throughput (ms/op, lower is better). JMH, 3 forks, 5+5 iterations, JDK 25.0.4 Temurin. Jackson version: 3.2.3.

Input jjq Jackson 3 jjq speedup
Production 14MB 12.2 ms 18.2 ms 1.50x
flat 1MB 1.77 ms 2.00 ms 1.13x
strings 1MB 0.88 ms 1.55 ms 1.76x
numbers 1MB 2.09 ms 2.92 ms 1.40x
nested 1MB 1.61 ms 2.37 ms 1.47x

jjq serializes 1.1-1.8x faster than Jackson 3 across all inputs. The speedup comes from pre-computed JSON key forms for interned field names (no escape scanning), type-specialized appendTo dispatch, and pre-sized StringBuilder buffers based on the source byte length (eliminates repeated buffer doubling for large documents).

CLI Performance: jjq native-image vs jq 1.8.1

GraalVM native-image comparison on the 14MB production file (hyperfine, best of 3+ warmup runs):

Test jq 1.8.1 jjq (native) Notes
Startup ('.' /dev/null) 1.4 ms 1.7 ms Both sub-2ms
Field access (.user) 122 ms 168 ms Parse-dominated
Deep field (.a.b[0].c) 122 ms 168 ms Parse-dominated
Object construction 123 ms 168 ms Parse-dominated
Identity round-trip (parse + serialize) 245 ms 213 ms jjq 15% faster

For CLI one-shot usage, jq 1.8.1's C parser is ~36% faster on parse-dominated workloads. jjq wins on full round-trips (parse + serialize) due to faster serialization. The native-image binary is 15 MB vs jq's 36 KB.

jjq's strength is the library use case — parse once, query many times. A 14MB upload is parsed once and queried with dozens of jq expressions. The interning, zero-allocation queries, and pre-compiled bytecode VM amortize across all queries, achieving 3 ns field access with zero garbage. This is not measurable in CLI one-shot benchmarks where parse time dominates.

Architecture

jq expression string
        |
   [Lexer]              Hand-written, keyword-aware
        |
   Token stream
        |
   [Parser]              Pratt parser (top-down operator precedence)
        |
   AST (JqExpr)          ~35 sealed record types
        |
   [Compiler]            AST -> Bytecode with fusion + folding
        |
   [VirtualMachine]      Stack-based, FORK/BACKTRACK for generators
        |
   Output (JqValue)

Bytecode VM

  • 75 opcodes (as of 2026-09-12 — see Opcode.java) with fused iteration (COLLECT_ITERATE, REDUCE_ITERATE, COLLECT_SELECT_ITERATE)
  • 9 inlined builtin opcodes (as of 2026-09-12 — see JqProgram.isInlinableBuiltin: length, type, keys, not, tostring, reverse, sort, abs, empty)
  • Compound instructions (DOT_FIELD2 for .a.b, BUILD_OBJECT with pre-computed layouts)
  • Whole-program shape detection — IDENTITY, FIELD_ACCESS, FIELD_ACCESS2, PIPE_FIELD_ARITH, BUILTIN bypass the VM loop entirely
  • Constant folding and peephole optimization at compile time
  • Pre-allocated growable stacks with pre-ensured capacity for hot loops

Value System

All JqValue types implement Serializable for Hibernate second-level cache support. Singletons (JqNull.NULL, JqBoolean.TRUE/FALSE, cached JqNumber instances) preserve identity across serialization via readResolve().

Type Implementation Key optimization
JqNull Singleton Zero allocation
JqBoolean TRUE/FALSE constants Zero allocation
JqNumber long fast-path with cache [-128, 1023], double for decimals, BigDecimal fallback. of(Number) accepts any Number subtype. Direct digit accumulation avoids new BigDecimal() for 99% of numbers
JqString Deferred: holds (source, start, end) reference, materializes lazily. Serialization proxy materializes before writing. Zero-copy serialization via sb.append(source, start, end) for untouched strings
JqArray List<JqValue> via raw JqValue[] ofTrusted() avoids defensive copying
JqObject Parallel String[] keys + JqValue[] values, Builder for zero-intermediate construction. Serialization proxy converts map-backed to array-backed. Linear scan for ≤32 keys, hash index for larger objects. Interned field names enable reference equality. Pre-computed "key": JSON form eliminates escapeJson scanning. Copy-on-write with()/without()/merge()/deepMerge(). forEach(BiConsumer) for zero-allocation iteration.

Parser Optimizations

  • byte[]-based parser (JqValues.parse(byte[])) — parses UTF-8 bytes directly, no intermediate String
  • SWAR scanning — finds " and \ in 8 bytes per iteration using Netty-style bit manipulation
  • Deferred string values — string values hold source references, materialized only when accessed
  • Field name interning — open-addressing hash table (4096 slots, 8-probe linear probing, plus per-thread L1 with 256 slots and 2 probes). Keys hash with a dependency-free 64-bit word hash (fmix64 over first/last 8 bytes, length, and middle words for long keys) fused into the 8-byte SWAR delimiter scan — no serial 31*h+b recurrence. Slots verify with (w0, wLast) 64-bit word comparisons plus 8-byte middle loads for keys >16 bytes. Cache hits return the same String instance without substring(). A lazy secondary table keyed by String.hashCode() keeps pre-computed "key": JSON forms O(1) for serialization.
  • Vectorized schema key matching — opt-in CompiledKeys parsing matches expected keys with Arrays.equals (C2 vectorizedMismatch intrinsic) plus a closing-quote check; keys containing escapable characters decline to the full path
  • Bulk UTF-8 validation — Utf8.validate resumes 32-byte SWAR ASCII skipping after multibyte sequences (5x on early-Unicode, 2.3x on mixed documents like twitter.json) while staying on the straight scalar path across dense Unicode
  • On-demand path extraction (JqProgram.apply(byte[])) — compile-time path plans (BytePathPlan) drive a zero-allocation SWAR skipper (JsonByteSkipper) that walks raw bytes, skipping unmatched strings and containers structurally and materializing only matched values. Strict variant (applyStrict) gates the fast path with a whole-document grammar validator (StrictByteValidator) that falls back to the full strict parser on any rejection, keeping results and errors identical
  • Optional SIMD kernels — jjq-vector (JDK 27+, opt-in) registers four Vector API kernels via ServiceLoader: a container skipper (5.9–8.2× over SWAR; 12–24 GB/s), a single-pass block-windowed strict validator for compact string and numeric KV runs (~3× over scalar on 14 MB string docs, ~2× on numeric telemetry), a clean-string validator for declined documents, and an escape-copy kernel for long strings. jjq-core stays dependency-free: without the module, the scalar paths run unchanged
  • Direct digit accumulation — integers and decimals parsed to long/double without BigDecimal or substring() for numbers with ≤15 significant digits
  • Thread-local buffer reuse — both char-based (StringBuilder) and byte-based (BytOutput) serialization buffers grow once and are reused across calls
  • Direct byte serialization (JqValues.serializeToBytes(JqValue)) — serializes directly to UTF-8 bytes without intermediate String. Deferred-bytes strings copy raw source bytes (zero encoding). Interned field names use pre-computed byte forms. Numbers serialize directly to ASCII digits.

Building

# Requires Java 21+
mvn clean install

# Run tests only
mvn test

# Build CLI
mvn package -pl jjq-cli

# Build native binary (requires GraalVM 21+)
mvn package -pl jjq-core,jjq-cli -Pnative -DskipTests

# Run benchmarks
mvn package -pl jjq-core,jjq-jackson,jjq-fastjson2,jjq-benchmark -DskipTests
java --enable-preview -jar jjq-benchmark/target/jjq-benchmark-*.jar

# Run specific benchmark class
./scripts/run-benchmarks.sh JsonParseComparisonBenchmark

# Run with allocation profiling
java --enable-preview -jar jjq-benchmark/target/jjq-benchmark-*.jar \
  JsonProductionBenchmark -prof gc -rf json -rff results.json

Supported jq Features

  • Identity (.), field access (.foo, .a.b.c), indexing (.[0], .[2:5])
  • Pipes (|), comma (,), parentheses
  • Array/object construction ([...], {...}, computed keys)
  • String interpolation ("Hello \(.name)")
  • Arithmetic (+, -, *, /, %), comparison, logical operators
  • Recursive object merge (* operator)
  • Alternative operator (//)
  • Optional operator (.foo?, .[]?)
  • if-then-elif-else-end
  • try-catch
  • Variable binding (. as $x | ...)
  • Destructuring bind (. as [$a, $b] | ..., . as {name: $n} | ...)
  • reduce, foreach (with destructuring pattern support)
  • Function definitions (def f(x): ...;) with proper closure scoping
  • label-break
  • Assignment operators (|=, +=, -=, *=, /=, %=, //=)
  • Path expressions (path(), getpath, setpath, delpaths, del)
  • Recursive descent (..)
  • Format strings (@base64, @uri, @csv, @tsv, @html, @json)
  • All standard builtins (168 functions, as of 2026-09-12)

Known Limitations

jjq passes 504 of 525 upstream jq tests (96.0%, as of 2026-09-12). The remaining differences:

Module system (import / include / modulemeta)

jjq does not implement jq's module system. The import, include, and modulemeta keywords are not supported (12 skipped tests).

Big integer precision

jq uses arbitrary-precision integers internally. jjq uses long with BigDecimal fallback, which can produce slightly different results for integers beyond 2^53 (6 skipped tests). Normal-range arithmetic works correctly.

Internal string functions

jq's internal _strindices function is not implemented (2 skipped tests).

Minor error message differences

fromjson parse errors report a different column number than jq for certain invalid JSON (1 skipped test).

Non-finite numbers (NaN/Infinity)

jq has no non-finite values (it clamps or maps them away); YAML and lenient JSON can still put them in a tree, so their handling is defined here rather than left implicit:

Stage Behavior
Parse (value: .inf) typed non-finite node (JqNumber)
Queries exact IEEE arithmetic (inf + 1 is inf); abs, comparisons, isnan work
JSON output null (jq-compatible; Jackson's unquoted literals are unreadable here)
YAML output .inf / -.inf / .nan (round-trips)
Bind double exact value
Bind String source text (".inf")
Bind int / long / BigDecimal ShapeMismatchException (no silent zero)

Note: values display as null (that is the JSON rendering above), but the tree holds real non-finites — check with a double binding or isnan, not printed output.

Documentation

License

This project is licensed under the Apache License 2.0.

About

No description, website, or topics provided.

Resources

Stars

5 stars

Watchers

0 watching

Forks

Releases

Packages

Contributors

Languages