Constructing a JSON object from a bash associative array

There are many possibilities, but given that you already have written a bash for loop, you might like to begin with this variation of your script: #!/bin/bash # Requires bash with associative arrays declare -A dict dict[“foo”]=1 dict[“bar”]=2 dict[“baz”]=3 for i in “${!dict[@]}” do echo “$i” echo “${dict[$i]}” done | jq -n -R ‘reduce inputs … Read more

Create JSON using jq from pipe-separated keys and values in bash

Prerequisite For all of the below, it’s assumed that your content is in a shell variable named s: s=”CONTAINER|CPU%|MEMUSAGE/LIMIT|MEM%|NETI/O|BLOCKI/O|PIDS nginx_container|0.02%|25.09MiB/15.26GiB|0.16%|0B/0B|22.09MB/4.096kB|0″ What (modern jq) # thanks to @JeffMercado and @chepner for refinements, see comments jq -Rn ‘ ( input | split(“|”) ) as $keys | ( inputs | split(“|”) ) as $vals | [[$keys, $vals] | … Read more

Split a JSON file into separate files

This should give you a start: for f in `cat input.json | jq -r ‘keys[]’` ; do cat input.json | jq “.$f” > $f.json done or when you insist on more bashy syntax like some seem to prefer: for f in $(jq -r ‘keys[]’) ; do jq “.[\”$f\”]” < input.json > “$f.json” done < input.json

using jq to assign multiple output variables

You can use separate variables with read : read var1 var2 var3 < <(echo $(curl -s ‘https://api.github.com/repos/torvalds/linux’ | jq -r ‘.id, .name, .full_name’)) echo “id : $var1” echo “name : $var2” echo “full_name : $var3” Using array : read -a arr < <(echo $(curl -s ‘https://api.github.com/repos/torvalds/linux’ | jq -r ‘.id, .name, .full_name’)) echo “id : … Read more

Reusable function to group_by but return an object with group as key

Here’s a variant using reduce instead of group_by: reduce .[] as $m ({}; .[$m.country] += [$m]) Demo Or as a defined function: def grp(f): reduce .[] as $m ({}; .[$m|f] += [$m]); grp(.country) Demo { “germany”: [ { “name”: “anna”, “country”: “germany” }, { “name”: “lisa”, “country”: “germany” } ], “usa”: [ { “name”: “john”, … Read more

How to get key names from JSON using jq

You can use: jq ‘keys’ file.json Complete example $ cat file.json { “Archiver-Version” : “Plexus Archiver”, “Build-Id” : “”, “Build-Jdk” : “1.7.0_07”, “Build-Number” : “”, “Build-Tag” : “”, “Built-By” : “cporter”, “Created-By” : “Apache Maven”, “Implementation-Title” : “northstar”, “Implementation-Vendor-Id” : “com.test.testPack”, “Implementation-Version” : “testBox”, “Manifest-Version” : “1.0”, “appname” : “testApp”, “build-date” : “02-03-2014-13:41”, “version” : … Read more