乐闻世界logo
搜索文章和话题

How to filter by string in JSONPath?

1个答案

1

Filtering by string in JSONPath is a highly practical feature that helps developers precisely locate the required data nodes when processing JSON data. JSONPath's query syntax is similar to XPath, a path expression language for XML. Filtering strings typically involves using comparison operators to match specific text.

Basic Syntax

In JSONPath, you can use the [?()] filter expression for string filtering. Here is a general example demonstrating how to use this method:

json
{ "store": { "book": [ { "category": "reference", "author": "Nigel Rees", "title": "Sayings of the Century" }, { "category": "fiction", "author": "Evelyn Waugh", "title": "Sword of Honour" }, { "category": "fiction", "author": "Herman Melville", "title": "Moby Dick", "isbn": "0-553-21311-3" }, { "category": "fiction", "author": "J. R. R. Tolkien", "title": "The Lord of the Rings", "isbn": "0-395-19395-8" } ] } }

Example: Filtering by Author Name

Suppose you want to find all books with the author name 'Herman Melville'. In JSONPath, you can write:

plaintext
$.store.book[?(@.author=='Herman Melville')]

This expression means: "Starting from the root node, traverse to the store node, then to the book array, and filter to include only items where the author attribute value equals 'Herman Melville'."

More Complex Filtering Conditions

You can also filter based on multiple conditions, for example, to find all books with category 'fiction' and author name containing 'J. R. R. Tolkien':

plaintext
$.store.book[?(@.category=='fiction' && @.author=='J. R. R. Tolkien')]

This expression uses the logical operator && to combine two conditions.

Using Regular Expressions for Filtering

In some implementations, JSONPath supports filtering using regular expressions, which makes string matching more flexible and powerful:

plaintext
$.store.book[?(@.author =~ /.*Tolkien.*/i)]

This filters all books where the author name contains 'Tolkien', with the i flag indicating case-insensitive matching.

Conclusion

By using JSONPath's filter expressions, you can flexibly query and process JSON data. Whether it's simple string comparisons or complex inclusion logic and regular expression queries, JSONPath provides robust support. In practical development, this capability significantly simplifies the complexity of data processing.

2024年8月9日 02:43 回复

你的答案