A jq implementation in MoonBit
# Clone the repository
git clone https://github.com/moonbit-community/moobit-jq.git
cd moobit-jq
# Run tests to verify installation
moon test///|
/// Helper function: Evaluate a jq query and return newline-separated results.
/// This mimics the command-line jq tool's behavior.
fn jq(query : String, input : String) -> String raise {
let expr = @parser.parse(query)
let json = @json.parse(input[:])
@ast.eval(expr, json).collect().map(fn(v) { v.to_string() }).join("\n")
}
**Explanation**: The `select(.age >= 18)` filters users 18 or older, then `{name: .name, email: .email}` constructs new objects with only those fields.
### 2. Optional Access with Defaults
Handle missing fields gracefully using `?` and `//`:
```mbt check
inspect(
jq(query, input),
content=(
#|String("(unknown)")
),
)
}
**Explanation**: `map(. * 2)` doubles each number, then `add` sums them all: `(1*2 + 2*2 + 3*2) = 12`.
### 4. Filter Logs by Level
Extract specific log messages based on severity:
```mbt check
///|
test "readme: extract error messages" {
///|
inspect(
jq(query, input),
content=(
#|String("disk full")
#|String("timeout")
),
)
}///|
test "readme: array slicing" {
let query = ".items[1:3] | reverse"
let input =
#|{ "items": [10, 20, 30, 40, 50] }
inspect(
jq(query, input),
content=(
#|Array([Number(30), Number(20)])
),
)
}///|
test "readme: recursive descent" {
let query = ".. | select(type == \"number\")"
let input =
#|{
#| "a": 1,
#| "b": { "c": 2, "d": { "e": 3 } }
#|}
inspect(
jq(query, input),
content=(
#|Number(1)
#|Number(2)
#|Number(3)
),
)
}moobit-jq/
├── moon.mod.json # Module metadata
├── README.mbt.md # This file (executable documentation)
├── ast/ # AST + streaming evaluator + integration tests
├── parser/ # Parser (includes lexer)
├── json/ # JSON value wrapper# Run all tests (415+ tests)
moon test
# Run specific package tests
moon test -p parser
moon test -p ast
# Type-check without running tests
moon check
# Type-check this README
moon check README.mbt.md
# Update test snapshots
moon test --update# Format code
moon fmt
# Generate package interfaces
moon info
# Check for warnings
moon check --target all
## Building and testing
This repo is a MoonBit module with multiple packages; run commands against specific package paths:
```bash
# Type-check a package (and its deps)
moon check --package-path parser
moon check --package-path ast
# Run tests
moon test -p ast -p json -p parser
# Update snapshots (expect tests)
moon test -p ast -p json -p parser --update
# Generate/update public interfaces (.mbti)
moon infoA jq implementation in MoonBit