Skip to main content
Version: v1.12.0

order

Function

order reorder record fields

Synopsis

order(val: any, t: type) -> any

Description

The order function changes the order of fields in the input value val to match the order of records in type t. Ordering is useful when the input is in an unordered format (such as JSON), to ensure that all records have the same known order.

If val is a record (or if any of its nested values is a record):

  • order passes through "extra" fields not present in the type value,
  • extra fields in the input are added to the right-hand side, ordered lexicographically,
  • missing fields are ignored, and
  • types of leaf values are ignored, i.e., there is no casting.

Note that lexicographic order for fields in a record can be achieved with the empty record type, i.e.,

order(val, <{}>)
Note

Record expressions can also be used to reorder fields without specifying types (example).

Examples

Order a record

echo '{b:"foo", a:1}' | zq -z 'order(this, <{a:int64,b:string}>)' -

produces

{a:1,b:"foo"}

Order fields lexicographically

echo '{c:0, a:1, b:"foo"}' | zq -z 'order(this, <{}>)' -

produces

{a:1,b:"foo",c:0}

TBD: fix this bug or remove example...

Order an array of records

echo '[{b:1,a:1},{a:2,b:2}]' | zq -z 'order(this, <[{a:int64,b:int64}]>)' -

produces

[{a:1,b:1},{a:2,b:2}]

Non-records are returned unmodified

echo '10.0.0.1 1 "foo"' | zq -z 'fill(this, <{a:int64,b:int64}>)' -

produces

10.0.0.1
1
"foo"