Bash Looping JQ

· 121 words · 1 minute read
#!/usr/bin/env bash

FAKE_API_RESPONSE='{"name":"package1.file1.js","content":"var foo = {\n\t\"bar\" = \"banana\"\n}\nconsole.log(foo)"}'

echo $FAKE_API_RESPONSE | jq -r '[.name,.content] | @tsv' |
    while IFS=$'\t' read -r apiname script; do
        dirname="./$(echo "$apiname" | cut -d '.' -f 1)"
        filename="$(echo $apiname | echo "$dirname/$(cut -d '.' -f 2).js")"
        mkdir -p $dirname
        echo "$script" | sed 's/\\n/\
/g' | sed 's/\\t/\  /g' > $filename
    done

I’m working with an API that returns several JSON objects, each object as a new line. Not a list of objects.

Each object has two fields I care about: a package name and the contents of a file.

This script reads each JSON object, parses a .-delimited package name into a directory/package combination, and then parses the file and saves it to that file.