Skip to content

Instantly share code, notes, and snippets.

@mrlesmithjr
Last active February 22, 2022 22:39
Show Gist options
  • Star 4 You must be signed in to star a gist
  • Fork 2 You must be signed in to fork a gist
  • Save mrlesmithjr/c42ebb99a01e8eeeca6a5eb4fa52f852 to your computer and use it in GitHub Desktop.
Save mrlesmithjr/c42ebb99a01e8eeeca6a5eb4fa52f852 to your computer and use it in GitHub Desktop.
dig results to parsable json
foo=$(dig google.com +nocomments +noquestion +noauthority +noadditional +nostats | awk '{if (NR>3){print}}'| jq -R 'split("\t") |{Name:.[0],TTL:.[2],Class:.[3],Type:.[4],IpAddress:.[5]}' | jq --slurp .) | jq -n --argjson v $foo '{"foo": $v}'
@mrlesmithjr
Copy link
Author

{
  "foo": [
    {
      "Name": "google.com.",
      "TTL": "29",
      "Class": "IN",
      "Type": "A",
      "IpAddress": "64.233.176.113"
    },
    {
      "Name": "google.com.",
      "TTL": "29",
      "Class": "IN",
      "Type": "A",
      "IpAddress": "64.233.176.100"
    },
    {
      "Name": "google.com.",
      "TTL": "29",
      "Class": "IN",
      "Type": "A",
      "IpAddress": "64.233.176.139"
    },
    {
      "Name": "google.com.",
      "TTL": "29",
      "Class": "IN",
      "Type": "A",
      "IpAddress": "64.233.176.138"
    },
    {
      "Name": "google.com.",
      "TTL": "29",
      "Class": "IN",
      "Type": "A",
      "IpAddress": "64.233.176.101"
    },
    {
      "Name": "google.com.",
      "TTL": "29",
      "Class": "IN",
      "Type": "A",
      "IpAddress": "64.233.176.102"
    }
  ]
}

@heartsinaustin
Copy link

Can you look if your current foo works still? Im trying to use it and I get the following:

jq: invalid JSON text passed to --argjson

If I take off the " | jq -n --argjson v $foo '{"foo": $v}'" part at the end I get closer to what I need.

The above action will not put the "foo": part in nor will it put commas in between }, {

I am using ver 1.5 hope you can help. Today is my first day trying to use jq so Im pretty sure what you have above worked at least at some point.

Thanks for any help you can offer.

@luisdavim
Copy link

try:

#!/usr/bin/env bash
set -- "${1:-$(</dev/stdin)}" "${@:2}"
if [ -z "$1" ]; then
  echo "missing arguments"
  dig --help
  exit 1
fi
dig $@ +noall +answer | awk '{if (NR>3){print}}'| tr '[:blank:]' ';'| jq -R 'split(";") |{Name:.[0],TTL:.[1],Class:.[2],Type:.[3],IpAddress:.[4]}' | jq --slurp '.'

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment