JSON Operators:-


In JSON, you can use various path operators to navigate and extract values from the JSON structure. Here's a breakdown of the most common JSON Path operators along with examples of how you can use them:


1. Dot Notation (.)

The dot notation is used to access a child element in the JSON object.

Example:

JSON:

json

Copy

{

"person": {

"name": "John",

"age": 30,

"address": {

"city": "New York",

"zip": "10001"

}

}

}

JSON Path:

$.person.name // Outputs "John"

$.person.age // Outputs 30


2. Bracket Notation ([])


Bracket notation is often used to access array elements or key names that contain spaces or special characters.

Example:

JSON:

{ "people":

[ { "name": "John", "age": 30 },

{ "name": "Jane", "age": 25 },

{ "name": "Mike", "age": 35 } ]

}


JSON Path:

$.people[0].name // Outputs "John"

$.people[1].age // Outputs 25


3. Wildcard (*)

The * operator is used to select all elements in an array or all child elements in an object.

Example:

JSON:

{ "company":

{ "employees": [

{ "name": "John", "age": 30 },

{ "name": "Jane", "age": 25 },

{ "name": "Mike", "age": 35 } ] }

}

JSON Path:

$.company.employees[*].name // Outputs ["John", "Jane", "Mike"]

$.company.employees[*].age // Outputs [30, 25, 35]


4. Filter (?() or [?()])

The filter expression allows you to filter the elements of an array based on a condition.

Example:

JSON:

{ "people":

[ { "name": "John", "age": 30 },

{ "name": "Jane", "age": 25 },

{ "name": "Mike", "age": 35 } ]

}


JSON Path:

$.people[?(@.age > 30)].name // Outputs ["Mike"]

$.people[?(@.age < 30)].name // Outputs ["Jane"]


5. Recursive Descent (..)

The .. operator searches recursively through all levels of the JSON structure to find matching nodes.

Example:

JSON:

{

"root":{

"a":1,

"b":{

"c":2,

"d":3

},

"e":{

"f":{

"g":4

}

}

}

}

JSON Path:

$.root..c // Outputs [2]


6. Array Slice ([start:end])

The array slice operator is used to select a subset of elements from an array. You can specify a range using the start:end format.

Example:

JSON:


{ "numbers": [1, 2, 3, 4, 5, 6] }

JSON Path:

$.numbers[1:4] // Outputs [2, 3, 4]

$.numbers[:3] // Outputs [1, 2, 3]

$.numbers[3:] // Outputs [4, 5, 6]


7. Union ([,])

The union operator allows you to select multiple elements at once.

Example:

JSON:

{

"people":

[

{ "name": "John", "age": 30 },

{ "name": "Jane", "age": 25 },

{ "name": "Mike", "age": 35 }

]

}


$.people[0, 2].name // Outputs ["John", "Mike"]




要查看或添加评论,请登录

Amit Sharma的更多文章

社区洞察

其他会员也浏览了