Search code examples
jsonwindowsjqcmder

How to get JQ to retain comma separation between matched records in the output


I'm attempting to use windows cmder.exe (or standard command prompt) to execute jq commands for command-line JSON processor to transform and output existing JSON files I have saved. I've had success with returning data but now I'm curious about why there are no commas separating the matched records.

Given the the sample json

[
    {
      "name": "Bob",
      "location": "New York"
    },
    {
      "name": "Adam",
      "location": "Los Angeles"
    },
    {
      "name": "Jill",
      "location": "Chicago"
    }
]

When I retrieve matches for locations of New York and Los Angeles..

jq ".[] | select((.location == \"New York\") or select(.location == \"Los Angeles\"))" sample.json

I see the output:

{
  "name": "Bob",
  "location": "New York"
}
{
  "name": "Adam",
  "location": "Los Angeles"
}

My goal is interchangeably depending on my needs either (a) display results via the command line or (b) output to a new file such as

jq ".[] | select((.location == \"New York\") or select(.location == \"Los Angeles\"))" sample.json > newsample.json

So I need a fix in order to see the expected look below without physically changing the original sample.json file:

{
  "name": "Bob",
  "location": "New York"
},
{
  "name": "Adam",
  "location": "Los Angeles"
}

or even this if it's possible

[
  {
      "name": "Bob",
      "location": "New York"
  },
  {
      "name": "Adam",
      "location": "Los Angeles"
  }
]

Solution

  • .[] iterates the elements of an array and returns a stream of JSON entities. You cannot take a stream of JSON entities and claim its valid JSON: {"a":1},{"b":2} is not valid JSON nor a valid stream. [{"a":1},{"b":2}] is a valid JSON document containing a single array.

    If you want to return an array, use map(f) to apply the filter f to every element in the array. map(f) is equivalent to [.[] | f] (and in fact implemented as such).

    map(select(.location == "New York" or .location == "Los Angeles"))