{ } jq-lite

Perl integration

On this pageMinimal exampleFiltering dataWorking with structured resultsConstructor variablesDeclaring JQ::Lite as a dependencyError handlingPublic API boundaryRecommended integration checklist
このページの目次最小の使用例データの絞り込み構造化された結果の扱いコンストラクターで変数を渡す依存関係の宣言エラー処理公開APIの境界組み込み時の確認事項

外部のjqバイナリを起動せず、アプリケーションやCPAN配布物からjqに似たJSONクエリを実行できます。

最小の使用例

use strict;
use warnings;
use JQ::Lite;

my $json = <<'JSON';
{"users":[{"name":"Alice"},{"name":"Bob"}]}
JSON

my $jq = JQ::Lite->new;
my @names = $jq->run_query($json, '.users[].name');
print "$_\n" for @names;

run_queryはPerlのリストを返します。JSONオブジェクトはハッシュ参照、配列は配列参照です。

データの絞り込み

use JQ::Lite;
my $jq = JQ::Lite->new;
my @names = $jq->run_query(
    $json,
    '.users[] | select(.active == true) | .name'
);

JSONテキストを受け取るAPIクライアント、取り込み処理、CI補助、ログ処理などで使えます。

構造化された結果の扱い

my ($user) = $jq->run_query(
    $json,
    '.users[] | select(.id == 42)'
);
if (ref $user eq 'HASH') {
    print $user->{name}, "\n";
}

1つのクエリから0個・1個・複数の結果が出るため、リストコンテキストを意識して使用してください。

コンストラクターで変数を渡す

jq形式の事前定義変数はvarsで指定できます。

my $jq = JQ::Lite->new(
    vars => { wanted_id => 42 },
);

安定したLibrary API仕様の対象は、文書化したオプションだけです。

依存関係の宣言

ExtUtils::MakeMakerを使う配布物では以下のように指定できます。

WriteMakefile(
    NAME => 'My::Module',
    PREREQ_PM => { 'JQ::Lite' => '2.50' },
);

必要な動作を提供する最小バージョンを選び、常に最新版へ固定する必要はありません。以下の構造化エラークラスは2.50以降で利用できます。

cpanfileでは以下のように指定します。

requires 'JQ::Lite', '>= 2.50';

エラー処理

人間向けの文字列化を維持した、構造化例外を提供します。

  • JQ::Lite::Error::Input:run_queryへ渡したJSONが不正。
  • JQ::Lite::Error::Parse:クエリの構文が不正。
  • JQ::Lite::Error::Evaluation:評価・実行時の失敗。

すべてJQ::Lite::Errorを継承し、messageとcategoryを取得できます。

my @results;
my $ok = eval {
    @results = $jq->run_query($json, $query);
    1;
};
if (!$ok) {
    my $error = $@;
    if (ref($error) && $error->isa('JQ::Lite::Error')) {
        warn $error->category . ': ' . $error->message . "\n";
    }
    else {
        warn $error;
    }
}

例外は診断メッセージへ文字列化されるため、既存の$@の記録・表示にも使えます。厳密な文言ではなく、文書化したクラスと分類に依存してください。Library API仕様に保証内容を掲載しています。

公開APIの境界

下流の配布物はJQ::Lite本体へ依存し、エラー分類には公開のJQ::Lite::Error階層を使えます。JQ::Lite::Parser、JQ::Lite::Filters、JQ::Lite::Utilなどは、明示的に公開されない限り内部実装です。

組み込み時の確認事項

  • 内部の構文解析・フィルター・補助モジュールではなく、JQ::Liteへ依存する。
  • リストコンテキストで呼び、0個・複数個の結果に対応する。
  • 使用する機能に基づいて最小バージョンを決める。
  • メッセージの解析ではなく、公開の例外クラス・分類で失敗を判断する。
  • 新しい公開動作を利用する前にLibrary API仕様を確認する。

JQ::Lite can be used directly by applications and CPAN distributions that need jq-like JSON querying without invoking an external jq binary.

Minimal example

use strict;
use warnings;
use JQ::Lite;

my $json = <<'JSON';
{"users":[{"name":"Alice"},{"name":"Bob"}]}
JSON

my $jq = JQ::Lite->new;
my @names = $jq->run_query($json, '.users[].name');

print "$_\n" for @names;

run_query returns a Perl list. JSON objects are returned as hash references and JSON arrays as array references.

Filtering data

use JQ::Lite;

my $jq = JQ::Lite->new;
my @names = $jq->run_query(
    $json,
    '.users[] | select(.active == true) | .name'
);

This is useful inside API clients, importers, CI helpers, log processors, and other modules that already receive JSON text.

Working with structured results

my ($user) = $jq->run_query(
    $json,
    '.users[] | select(.id == 42)'
);

if (ref $user eq 'HASH') {
    print $user->{name}, "\n";
}

Callers should use list context deliberately because one query may emit zero, one, or multiple results.

Constructor variables

Predeclared jq-style variables can be supplied with vars:

my $jq = JQ::Lite->new(
    vars => {
        wanted_id => 42,
    },
);

Only documented constructor options are part of the stable Library API contract.

Declaring JQ::Lite as a dependency

For a distribution using ExtUtils::MakeMaker:

WriteMakefile(
    NAME => 'My::Module',
    PREREQ_PM => {
        'JQ::Lite' => '2.50',
    },
);

Choose the minimum JQ::Lite version that provides the behavior your distribution actually requires rather than automatically pinning to the newest release. The structured Library API error classes documented below are available from version 2.50.

For cpanfile:

requires 'JQ::Lite', '>= 2.50';

Error handling

Library failures expose structured exceptions while preserving human-readable stringification:

  • JQ::Lite::Error::Input — invalid JSON input supplied to run_query
  • JQ::Lite::Error::Parse — malformed jq-lite query syntax
  • JQ::Lite::Error::Evaluation — query evaluation/runtime failure

All three inherit from JQ::Lite::Error and provide message and category accessors.

my @results;
my $ok = eval {
    @results = $jq->run_query($json, $query);
    1;
};

if (!$ok) {
    my $error = $@;

    if (ref($error) && $error->isa('JQ::Lite::Error')) {
        warn $error->category . ': ' . $error->message . "\n";
    }
    else {
        warn $error;
    }
}

Exception objects stringify to their diagnostic message, so existing code that logs or displays $@ continues to receive a useful message. Downstream code should depend on the documented class/category rather than exact message text.

See library-contract.md for the compatibility guarantees that apply to Library API callers.

Public API boundary

Downstream distributions should depend on the JQ::Lite package itself and may use the documented JQ::Lite::Error hierarchy for error classification.

Implementation packages such as JQ::Lite::Parser, JQ::Lite::Filters, and JQ::Lite::Util remain internal unless explicitly promoted to public API in the Library API contract.

Recommended integration checklist

  • Depend on JQ::Lite, not internal parser/filter/utility submodules.
  • Use run_query in list context and handle zero or multiple results.
  • Choose a minimum dependency version based on features actually used.
  • Detect failures using the documented JQ::Lite::Error classes/categories rather than parsing message strings.
  • Review the Library API contract before relying on newly introduced public behavior.