Skip to main content

You are not logged in. Your edit will be placed in a queue until it is peer reviewed.

We welcome edits that make the post easier to understand and more valuable for readers. Because community members review edits, please try to make the post substantially better than how you found it, for example, by fixing grammar or adding additional resources and hyperlinks.

Required fields*

6
  • 3
    Can you use keys_unsorted instead of keys to preserve the key order from the first object? Commented Oct 6, 2015 at 15:53
  • 2
    @outis - The preamble about streams is somewhat inaccurate. The simple fact is that jq filters are stream-oriented. That is, any filter can accept a stream of JSON entities, and some filters can produce a stream of values. There is no "new line" or any other separator between the items in a stream -- it's only when they're printed that a separator is introduced. To see for yourself, try: jq -n -c 'reduce ("a","b") as $s (""; . + $s)' Commented Dec 15, 2015 at 6:21
  • Did something happen between when this was written and now to render it incorrect? The problem seems to be in the map, which, breaks even on a toy example: $ echo '{"a":1,"b":2,"c":3}' |jq -r '(. | keys_unsorted) as $keys| $keys, map( [.[ $keys[] ] ])[] | @csv' outputs "a","b","c" jq: error (at <stdin>:1): Cannot index number with string "a" on jq-1.5. Commented Mar 20, 2017 at 20:58
  • 2
    @Wyatt: take a closer look at your data and the example input. The question is about an array of objects, not a single object. Try [{"a":1,"b":2,"c":3}]. Commented Mar 25, 2017 at 11:01
  • 1
    Working through the details of this solution taught me a LOT about jq! For anyone else struggling with the details, it may be helpful to play with "jq -cr '(.[0] | keys_unsorted) as $array_of_keys | $array_of_keys, (.[] | [ .[$array_of_keys[]] ]) | .'", since that's how the map filter is implemented. And remember that the "(foo) as $bar" variable assignment actually acts as a for-each that iterates over all the items in the (foo) expression (not an issue in this case, since we're pulling out the keys as a single item). Commented Jul 10, 2017 at 15:57