You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在JavaScript中读取环境变量?附JSON转HTML表格代码

Great question! The way you access environment variables in JavaScript depends entirely on where your code is running—whether it's in Node.js (like a backend script or build tool) or directly in a web browser. Let's break this down to fit your workflow of taking JSON from an env var and converting it to an HTML table:

1. If you're working in Node.js (backend/build-time)

Node.js exposes all environment variables via the process.env object. Here's how to integrate this with your workflow:

  • First, store your API's JSON response in an environment variable (make sure to handle quotes properly; using a here-string in Bash helps avoid escaping issues):
    # Capture curl output into an environment variable
    export API_JSON_RESPONSE=$(curl -s "https://your-api-endpoint.com/data")
    
  • Then in your Node.js code, read and parse the variable to use with your table-generation logic:
    // Parse the JSON from the environment variable
    const jsonData = JSON.parse(process.env.API_JSON_RESPONSE);
    
    // You can now use jsonData in place of the hardcoded `myBooks` array in your table code
    

2. If you're working in the browser (frontend code)

Browsers can't directly access system environment variables for security reasons. You'll need to pass the JSON data from the environment to the browser using one of these methods:

Option A: Inject the JSON as a global variable during build/serve

When serving your HTML file (from a backend or build script), embed the environment variable's value into a <script> tag to create a global variable. For example, if using an Express/EJS setup:

<!DOCTYPE html>
<html>
<head>
<title>Convert JSON Data to HTML Table</title>
<style>
th, td, p, input { font:14px Verdana; }
table, th, td { border: solid 1px #DDD; border-collapse: collapse; padding: 2px 3px; text-align: center; }
th { font-weight:bold; }
</style>
</head>
<body>
<input type="button" onclick="CreateTableFromJSON()" value="Create Table From JSON" />
<p id="showData"></p>

<!-- Inject the JSON from the environment variable -->
<script>
// Your backend/build tool replaces this placeholder with the actual env var value
const apiData = JSON.parse('<%= process.env.API_JSON_RESPONSE %>');
</script>
<script>
function CreateTableFromJSON() {
  // Replace hardcoded myBooks with the injected global variable
  var myBooks = apiData;

  // Rest of your table generation code remains the same
  var col = [];
  for (var i = 0; i < myBooks.length; i++) {
    for (var key in myBooks[i]) {
      if (col.indexOf(key) === -1) {
        col.push(key);
      }
    }
  }
  var table = document.createElement("table");
  var tr = table.insertRow(-1);
  for (var i = 0; i < col.length; i++) {
    var th = document.createElement("th");
    th.innerHTML = col[i];
    tr.appendChild(th);
  }
  for (var i = 0; i < myBooks.length; i++) {
    tr = table.insertRow(-1);
    for (var j = 0; j < col.length; j++) {
      var tabCell = tr.insertCell(-1);
      tabCell.innerHTML = myBooks[i][col[j]];
    }
  }
  var divContainer = document.getElementById("showData");
  divContainer.innerHTML = "";
  divContainer.appendChild(table);
}
</script>
</body>
</html>

If using modern build tools:

  • Webpack: Use the DefinePlugin to inject the JSON directly into your code.
  • Vite: Add the JSON to a .env file (prefix with VITE_ like VITE_API_JSON='[{"key":"value"}]'), then access it via JSON.parse(import.meta.env.VITE_API_JSON).

Option B: Skip the env var and fetch the JSON directly in the browser

If your API is publicly accessible, you can simplify things by fetching the data directly in your frontend code instead of using an environment variable:

async function CreateTableFromJSON() {
  try {
    // Fetch data directly from your API
    const response = await fetch("https://your-api-endpoint.com/data");
    var myBooks = await response.json();

    // Rest of your table generation code stays identical
    var col = [];
    for (var i = 0; i < myBooks.length; i++) {
      for (var key in myBooks[i]) {
        if (col.indexOf(key) === -1) {
          col.push(key);
        }
      }
    }
    var table = document.createElement("table");
    var tr = table.insertRow(-1);
    for (var i = 0; i < col.length; i++) {
      var th = document.createElement("th");
      th.innerHTML = col[i];
      tr.appendChild(th);
    }
    for (var i = 0; i < myBooks.length; i++) {
      tr = table.insertRow(-1);
      for (var j = 0; j < col.length; j++) {
        var tabCell = tr.insertCell(-1);
        tabCell.innerHTML = myBooks[i][col[j]];
      }
    }
    var divContainer = document.getElementById("showData");
    divContainer.innerHTML = "";
    divContainer.appendChild(table);
  } catch (error) {
    console.error("Error loading data:", error);
    document.getElementById("showData").innerHTML = "Failed to load table data.";
  }
}

内容的提问来源于stack exchange,提问作者themaster

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.13 07:41:13