Skip to content

Instantly share code, notes, and snippets.

@Swarag-N
Created October 10, 2024 19:01
Show Gist options
  • Save Swarag-N/c78ec4673100ccea95b009c101d988d9 to your computer and use it in GitHub Desktop.
Save Swarag-N/c78ec4673100ccea95b009c101d988d9 to your computer and use it in GitHub Desktop.
This script converts a .env file to a JSON format
sed 's/\r$//' .env | jq -Rn '
reduce (inputs | select(length > 0) | capture("(?<key>[^=]+)=(?<value>.*)") | select(.key != null)) as {$key, $value} ({};
if ($value | startswith("{") and endswith("}") and (try fromjson catch false)) then
.[$key] = ($value | fromjson)
else
.[$key] = $value
end
)
' > env.json

Dotenv to JSON Converter

This script converts a .env file to a JSON format. Here's a breakdown of how it works:

  1. Preprocessing with sed:

    sed 's/\r$//' .env
    • This command removes carriage returns (\r) at the end of each line in the .env file.
    • It handles both Windows (CRLF) and Unix (LF) line endings.
  2. JSON Conversion with jq:

    jq -Rn '...'
    • -R: Tells jq to read input as raw strings, not JSON.
    • -n: Tells jq not to read any input initially (we'll use inputs inside the script).
  3. Main Processing:

    reduce (inputs | select(length > 0) | capture("(?<key>[^=]+)=(?<value>.*)") | select(.key != null)) as {$key, $value} ({};
      if ($value | startswith("{") and endswith("}") and (try fromjson catch false)) then
        .[$key] = ($value | fromjson)
      else
        .[$key] = $value
      end
    )
    • inputs: Reads each line of the input.
    • select(length > 0): Skips empty lines.
    • capture("(?<key>[^=]+)=(?<value>.*)"): Splits each line into key and value.
    • select(.key != null): Ensures the line was successfully split.
    • reduce ... as {$key, $value} ({};...): Builds a JSON object from the key-value pairs.
    • The if statement checks if the value is a valid JSON object (starts with {, ends with }, and can be parsed as JSON).
      • If it is, it's parsed as JSON (allowing for nested structures).
      • If not, it's treated as a plain string.
  4. Output:

    > env.json
    • This redirects the output to a file named env.json.

Usage

  1. Save the script as dotenv_to_json_converter.sh
  2. Make it executable: chmod +x dotenv_to_json_converter.sh
  3. Run it: ./dotenv_to_json_converter.sh

The script will read from a file named .env in the current directory and output to env.json.

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