JSONPath Union Operator — Select Multiple Keys or Indices
Learn how to use the JSONPath union operator to select multiple properties or array indices in a single expression. Syntax, examples, and best practices.
Detailed Explanation
The Union Operator in JSONPath
The union operator allows you to select multiple properties or array indices in a single expression by listing them inside square brackets, separated by commas.
Syntax
$["key1", "key2", "key3"] // multiple properties
$.array[0, 2, 4] // multiple array indices
Selecting Multiple Properties
Given:
{
"name": "Alice",
"email": "alice@example.com",
"phone": "+1-555-0100",
"address": "123 Main St",
"age": 30
}
$["name", "email", "phone"] returns ["Alice", "alice@example.com", "+1-555-0100"] — only the three specified fields, ignoring the rest.
Selecting Multiple Array Indices
Given:
{
"logs": ["INFO: start", "DEBUG: init", "WARN: slow", "ERROR: timeout", "INFO: done"]
}
$.logs[0, 3, 4] returns ["INFO: start", "ERROR: timeout", "INFO: done"] — cherry-picking specific entries by their position.
Combining with Nested Paths
You can use the union operator at any level of a path:
$.users[0, 1].name // names of the first two users
$.config["db", "cache"].host // host values from db and cache sections
Union vs. Wildcard vs. Slice
| Operator | Syntax | Selection |
|---|---|---|
| Union | [0, 2] or ["a", "b"] |
Specific items |
| Wildcard | [*] |
All items |
| Slice | [0:3] |
Range of items |
The union operator gives you precise control over which elements to include, making it ideal when you know exactly which fields or positions you need.
Implementation Notes
- The result order matches the order you specify in the union, not the document order in all implementations.
- Some implementations require quotes around property names; others accept unquoted identifiers.
Use Case
Use the union operator when you need to extract a specific subset of fields from an API response — for example, selecting only name, email, and id from a user object, or picking specific log entries by index for debugging.