Basic usage of JsonPath

Basic usage of JsonPath

Basic usage of JsonPath

This article mainly introduces the basic syntax of JsonPath and demonstrates how to use it in Newtonsoft.Json.

Source of JsonPath

You can tell by its name that this guy is related to JSON documents. Just like XPath is to XML documents, JsonPath provides parsing capabilities for Json documents. By using JsonPath, you can easily find nodes and get the data you want. , JsonPath is the Json version of XPath.

JsonPath syntax

The syntax of JsonPath is relatively simple, and it adopts a friendly expression form of the development language. If you know C-like languages, you will not feel uncomfortable with JsonPath.

JsonPath syntax points:

  • $ Represents the root element of the document
  • @ Represents the current element of the document
  • .node_nameOr ['node_name']matching subordinate node
  • [index] Retrieve the elements in the array
  • [start:end:step] Support array slicing syntax
  • * As a wildcard, matches all members
  • .. Sub-recursive wildcard, matching all sub-elements of a member
  • (<expr>) Use expression
  • ?(<boolean expr>)Perform data filtering

The following table lists all supported syntax and compares XPath:

XPath

JsonPath

Description

/

$

Document root element

.

@

Current element

/

.or[]

Match subordinate elements

..

N/A

Match the superior element, JsonPath does not support this operator

//

..

Recursively match all child elements

*

*

Wildcard, matching subordinate elements

@

N/A

Matching attributes, JsonPath does not support this operator

[]

[]

Subscript operator, get elements according to index, XPath index starts from 1, JsonPath index starts from 0

|

[,]

Concatenation operator, concatenate multiple results into an array to return, you can use index or alias

N/A

[start:end:step]

Data slicing operation, XPath does not support

[]

?()

Filter expression

N/A

()

Script expression, use the underlying script engine, XPath does not support

()

N/A

Grouping, JsonPath does not support

note:

  • The index of JsonPath starts counting from 0
  • Strings in JsonPath are represented by single quotes, for example: $.store.book[?(@.category=='reference')]in'reference'

JsonPath example

The following is an example of the corresponding JsonPath, the code comes from https://goessner.net/articles/JsonPath/ , the JSON document is as follows:

{
    "store": {
        "book": [{
                "category": "reference",
                "author": "Nigel Rees",
                "title": "Sayings of the Century",
                "price": 8.95
            }, {
                "category": "fiction",
                "author": "Evelyn Waugh",
                "title": "Sword of Honour",
                "price": 12.99
            }, {
                "category": "fiction",
                "author": "Herman Melville",
                "title": "Moby Dick",
                "isbn": "0-553-21311-3",
                "price": 8.99
            }, {
                "category": "fiction",
                "author": "JRR Tolkien",
                "title": "The Lord of the Rings",
                "isbn": "0-395-19395-8",
                "price": 22.99
            }
        ],
        "bicycle": {
            "color": "red",
            "price": 19.95
        }
    }
}

Next we look at how to parse this document:

XPath

JsonPath

Result

/store/book/author

$.store.book[*].author

Author nodes of all books

//author

$..author

All author nodes

/store/*

$.store.*

All nodes under the store, book array and bicycle node

/store//price

$.store..price

All price nodes under the store

//book[3]

$..book[2]

Match the third book node

//book[last()]

$..book[(@.length-1)], or $..book[-1:]

Match the penultimate book node

//book[position()<3]

$..book[0,1], or $..book[:2]

Match the first two book nodes

//book[isbn]

$..book[?(@.isbn)]

Filter nodes with isbn field

//book[price<10]

$..book[?(@.price<10)]

Filter nodes with price<10

//*

$..*

Recursively match all child nodes

You can verify the execution effect of JsonPath at http://jsonpath.com/ .

Usage in Newtonsoft.Json

JsonPath is a language-independent expression language. The Newtonsoft.Json library provides support for JsonPath. It provides JObject.SelectToken()and JObject.SelectTokens()methods to use JsonPath to parse Json documents. The code is as follows:

//Create JObject object
var jObj = JObject.Parse(jsonString);
var books = jObj.SelectToken("$.store.book[?(@.category=='reference')]");

Reference documents:

Reference: https://cloud.tencent.com/developer/article/1511637 Basic usage of JsonPath-Cloud + Community-Tencent Cloud