0

I would like to convert 500+ json files to csv format using the solution provided in How to convert arbirtrary simple JSON to CSV using jq? but my json files are not in the same format as per the proposed solution.

Following represents a sample json file:

[
  {
    "jou_entry": {
      "id": 655002886,
      "units": 2
    }
  },
  {
    "jou_entry": {
      "id": 655002823,
      "units": 4
    }
  },
  {
    "jou_entry": {
      "id": 657553949,
      "units": 6
    }
  }
]

Where as the proposed solution requires the json in the following format:

[
  {
    "id": 655002886,
    "units": 2
  },
  {
    "id": 655002823,
    "units": 4
  },
  {
    "id": 657553949,
    "units": 6
  }
]

I am able to convert the json from source format to required format using the following jq filter

jq -r '[.[] | ."jou_entry"]' 

But I don't like the hard-coding of key "jou_entry" in the filter. As this will require individual key definition for so many files. I would like to have the conversion without the hard-coded value.

How can I do this? Please help

kishore
  • 541
  • 1
  • 6
  • 18

1 Answers1

0

This gets the desired output

jq '[.[] | .[]]'

Explanation from the manual. When .[] is used on an array, it returns all of the elements of an array. When it is used on an object it will return all the values of the object.

user197693
  • 1,935
  • 10
  • 8
  • 1
    It could be condensed further to `[.[][]]`. – Jeff Mercado Aug 23 '17 at 02:27
  • So it does! I can't find an example like that in the manual. If it isn't too much trouble, would you please explain how it works? Thanks. – user197693 Aug 23 '17 at 03:11
  • 1
    You don't necessarily need to use a pipe (`|`) between every simple expression. In a sense, `[]` here is an operand and it is operating on `.`. It's like eliminating `| .` from the end of a filter, it's unnecessary. You could combine many different types of operands on a single expression. e.g., `[to_entries[].key]` instead of `[to_entries | .[] | .key]` – Jeff Mercado Aug 23 '17 at 03:18
  • Got it. Thank you! – user197693 Aug 23 '17 at 05:38
  • Sorry, I mistyped, I meant to say that `[]` is like an _operator_. Not a big deal, I think you got my drift. – Jeff Mercado Aug 23 '17 at 05:42
  • Right. Thanks again. – user197693 Aug 23 '17 at 17:32