コンテンツへスキップ
uencoder

JSONPath で JSON をクエリする方法

JSONPath 式を使って、深くネストされた JSON から特定の値を抽出します。

问题

大きな深くネストされた JSON ドキュメントから、トラバーサルコードを自作せずに特定のフィールドを抽出する必要があります。

前提条件

  • JSON 構造の理解
  • パス式への習熟

ステップ

  1. 1. Learn the JSONPath syntax

    JSONPath uses dot notation for object keys ($.store.book) and brackets for array indices ([0]) or filters ([?(@.price < 10)]). The $ represents the root. Wildcards (*) match all elements. This is similar to XPath for XML.

    入力
    $.store.book[0].title
    输出
    first book's title
  2. 2. Write and test the expression

    Construct the JSONPath expression for the data you want to extract. Test it against your JSON document. Filters use @ to reference the current element. Multiple matches return an array of results.

    入力
    $.store.book[?(@.price<10)].title
    输出
    titles of books under $10
  3. 3. Handle edge cases

    Not all JSONPath implementations support the full spec. Filters, recursive descent ($..), and script expressions may vary. Check your implementation's capabilities. Handle missing paths gracefully — they return empty results, not errors.

    入力
    $..author
    输出
    all authors at any depth

期待される結果

JSONPath 式にマッチする値を JSON ドキュメントから抽出した結果。

よくあるエラー

Filter syntax not supported
Different JSONPath implementations support different filter syntaxes. Check the documentation for your specific implementation.
Path returns empty unexpectedly
Verify the path matches the JSON structure. Check for case sensitivity in keys and correct array indices.

トラブルシューティング指引

  • If the path returns nothing, print the JSON structure and verify each segment exists.
  • Use recursive descent ($..) to find keys at any depth if you are unsure of the exact path.

セキュリティ上の制限

  • JSONPath is a read-only query language. It does not modify data or execute code.
  • All querying is local.

関連ツール

関連用語

参考链接