This script converts a .env file to a JSON format. Here's a breakdown of how it works:
-
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.
- This command removes carriage returns (
-
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 useinputsinside the script).
-
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
ifstatement 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.
-
Output:
> env.json- This redirects the output to a file named
env.json.
- This redirects the output to a file named
- Save the script as
dotenv_to_json_converter.sh - Make it executable:
chmod +x dotenv_to_json_converter.sh - 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.