Update
I may have misunderstood what OP wanted. If it's a CSV with only one record then you can do:
y=Rule
x=$(aws s3api get-bucket-lifecycle-configuration --bucket test | jq '.Rules[]')
jq -nr --arg y "$y" --arg x "$x" '[$y, $x] | @csv' > sample.csv
Please take notice that the JSON stored in the second column of the CSV is not strictly valid as it's composed of a stack of objects instead of an array.
Prior answer
You can use jq
:
aws s3api get-bucket-lifecycle-configuration --bucket test |
jq -r '.Rules[] | [ (. | tostring) ] | @csv'
CSV output:
"{""Expiration"":{""Days"":7},""ID"":""Expire after 7 days"",""Filter"":{""Prefix"":""""},""Status"":""Enabled""}"
"{""Expiration"":{""Days"":1},""ID"":""Remove after 1 day"",""Filter"":{},""Status"":""Enabled""}"
But as @ZachYoung pointed out, as of now jq
doesn't have any easy way to generate pretty strings with tostring
or tojson
.
Personally I would stick to the compact version, but if the pretty formatting is really necessary then I would switch to ruby
instead of jq
(python is also an option but it lacks the one-liner thingy^^):
aws s3api get-bucket-lifecycle-configuration --bucket test |
ruby -rjson -rcsv -e 'puts "Rules", JSON.parse(ARGF.read)["Rules"].map{|rule| [JSON.pretty_generate(rule)].to_csv}'
CSV output:
Rules
"{
""Expiration"": {
""Days"": 7
},
""ID"": ""Expire after 7 days"",
""Filter"": {
""Prefix"": """"
},
""Status"": ""Enabled""
}"
"{
""Expiration"": {
""Days"": 1
},
""ID"": ""Remove after 1 day"",
""Filter"": {
},
""Status"": ""Enabled""
}"