Home > Net >  Shell - jq: Turning json list of `keys.childkeys` into list of lists
Shell - jq: Turning json list of `keys.childkeys` into list of lists

Time:02-06

I am using jq to parse a json file. This is the current output from jq:

[
 "key1.childk2",
 "key2.childk3"
]

I would like to turn this into a readable json format itself as list of lists like below:

    [ 
      ["key1","childk2"],
      ["key2","childk3"]
    ]

I would ideally prefer to do this with jq, however any other shell tool that can work on shell variables is fair game.

CodePudding user response:

You can use jq split filter:

jq '[.[] | split(".")]'
[
  [
    "key1",
    "childk2"
  ],
  [
    "key2",
    "childk3"
  ]
]

You should use it somewhere in the original jq command

CodePudding user response:

Here is a ruby to do that:

ruby -r json -e 'puts JSON.parse($<.read).map{|e| e.split(".")}.to_json' file

[["key1","childk2"],["key2","childk3"]]

Or if you want it pretty:

ruby -r json -e 'puts JSON.pretty_generate(
            JSON.parse($<.read).map{|e| e.split(".")})
' file
[
  [
    "key1",
    "childk2"
  ],
  [
    "key2",
    "childk3"
  ]
]

Or you can produce your precise format:

ruby -r json -e '
l=[]
JSON.parse($<.read).map{|e| l << e.split(".").to_s}
puts "[\n\t#{l.join(",\n\t")}\n]"
' file 
[
    ["key1", "childk2"],
    ["key2", "childk3"]
]

CodePudding user response:

With jq you can structurally turn the input into your desired JSON document using simple filters like map(./"."), but regarding the requested readability, the output wouldn't be exactly in your desired formatting.

Without any further flags, jq would pretty-print the output as:

[
  [
    "key1",
    "childk2"
  ],
  [
    "key2",
    "childk3"
  ]
]

Demo

Using the --compact-output or -c flag would compress the whole JSON document into one line, not just the elements of the outer array:

[["key1","childk2"],["key2","childk3"]]

Demo

So, if you really wanted to, you could also glue together the parts yourself as you like them to be formatted from within jq, but honestly, I would discourage you from doing so as by circumventing jq's JSON composer you might end up outputting invalid JSON.

jq -r '"[", "  "   ([.[] / "." | tojson] | .[:-1][]  = ",")[], "]"'
[
  ["key1","childk2"],
  ["key2","childk3"]
]

Demo

  •  Tags:  
  • Related