Using jq, HTTPie and the Firebase REST API to persist multiple objects with auto generated unique ids

Imagine a scenario where you've been developing locally with dummy data and at some point you decided to move this data to a Firebase instance.

Assuming your JSON file contents looks like the following.

[
  {
    "name": "Zapallo Anco",
    "price": 10,
    "unit": "Kg"
  },
  {
    "name": "Zuchini",
    "price": 10,
    "unit": "Kg"
  }
]

If your design doesn't require the use of unique identifiers for each object, fine, you're good to go ahead just using this simple command line.

cat data.json | http --verbose PUT https://my-firebase.firebaseio.com/test.json;

However, if you wish to assign a UID to each object inside your array, then you might want to do something more like the following. That way you're sure to get Firebase to associate your array objects with unique identifiers as key/value pairs inside a reference.

jq -r '.[] | tostring' data.json | while read line;
  do \
    echo ${line} | http --verbose POST https://my-firebase.firebaseio.com/test.json; \
    printf '\n\n'; \
  done;

If your app have security policies in place, then you might need to append a query parameter to the data url you pass to HTTPie. You'll need your Firebase app's secret which you can find under the Secrets panel of your Firebase app dashboard.

FIREBASE_SECRET="0f5some3b550a0a137dsecret478012a3"

echo '{"key":"value"}' | http --verbose POST https://my-firebase.firebaseio.com/test.json auth=="${FIREBASE_SECRET}";

Go ahead and try it. If you're on a Mac you can use Homebrew to $ brew install jq httpie and have these binaries available on your shell.

Comment bellow and let me know what you think. Have fun!

References