【问题标题】:Format output of writeJson in DenoDeno 中 writeJson 的格式输出
【发布时间】:2021-02-26 17:59:49
【问题描述】:

我正在使用 Deno 1.7,并希望将 JSON 文件的输出格式化为看起来像具有返回行和缩进/制表符的普通 JSON 文件。然而,这不是我在传递 JSON 样式字符串时看到的。


问题:为了获得不在一行上的文件(正确格式化 JSON),我应该改变什么?


注意:

供您参考,以下是最新的更新代码,根据下面给出的答案实际工作。

应用的结构是:

  • app.ts(入口点)
  • write-json.ts(写入 package.json 的模块)
  • deps.ts
  • .env
  • package.json(这是应用程序的输出)

我运行的 deno 命令是:

$ deno run --allow-read --allow-env --allow-write app.ts

// app.ts

import { config } from './deps.ts';
import { writePackageJsonFile } from './write-json.ts';

config({ export: true, safe: true });

const packageName: string = Deno.env.get('PACKAGE_NAME')!;
const content: string = Deno.env.get('PACKAGE_CONTENTS')!;
if(!packageName || !content){
  throw new Error("You must provide a valid file name and file content");
}

try {
  const parsedContent: any = JSON.parse(content);
  console.log(parsedContent)
  await writePackageJsonFile(packageName, parsedContent);
} catch (_) {
  throw new Error("The content provided for the file is not a valid JSON object");
}

// deps.ts

import { config } from 'https://deno.land/x/dotenv/mod.ts';
 
export { config };

// write-json.ts

import { writeJson, writeJsonSync } from 'https://deno.land/x/jsonfile/mod.ts';

export async function writePackageJsonFile(filename: string, contents: any) {
  await writeJson(filename, contents, { spaces: 2 });
}

// .env

PACKAGE_NAME="package.json"
PACKAGE_CONTENTS='{"name": "app", "version": "1.0.0", "scripts": { "start": "METEOR_SETTINGS=$(cat settings.json) node main.js" } }'

【问题讨论】:

  • 另外,环境变量中的JSON无效。它们的键和字符串值必须用双引号 "。所以把它们改成MY_VAR='{"key": "value"}'。然后先解析JSON,然后将其字符串化为-JSON.stringify(parsedJson, null, 2)。参考 - JSON.stringify()

标签: javascript json file environment-variables deno


【解决方案1】:

这是工作代码

import { config } from 'https://deno.land/x/dotenv/mod.ts';
import { writeJson } from 'https://deno.land/x/jsonfile/mod.ts';

// replace with correct type
type PackageJson = object

config({ export: true, safe: true });

async function writePackageJsonFile(filename: string, contents: PackageJson) {
  await writeJson(filename, contents, { spaces: 2 });
}

const packageName: string = Deno.env.get('PACKAGE_NAME')!;
const content: string = Deno.env.get('PACKAGE_CONTENTS')!;

const parsedContent: PackageJson = JSON.parse(content);
await writePackageJsonFile(packageName, parsedContent);
PACKAGE_NAME="package.json"
PACKAGE_CONTENTS='{"name": "app", "version": "1.0.0", "scripts": { "start": "METEOR_SETTINGS=$(cat settings.json) node main.js" } }'

问题在于writeJson 将对象作为要写入的内容而不是字符串。

因此,在最原始的问题中,您需要更改引号并解析 packageContents 并将解析后的内容传递给 writePackageJsonFile 函数。

【讨论】:

    【解决方案2】:

    您不需要任何库来执行此操作,Deno 具有用于编写和格式化 JSON 的内置函数,它就像以下一样简单

    // Use whatever package you want here to read the .env file
    
    const file_name = Deno.env.get('PACKAGE_NAME');
    const content = Deno.env.get('PACKAGE_CONTENTS');
    
    if(!file_name || !content){
      throw new Error("You must provide a valid file name and file content");
    }
    
    let json_object;
    try{
      json_object = JSON.parse(content);
    }catch(_){
      throw new Error("The content provided for the file is not a valid JSON object");
    }
    
    // Using two spaces to format
    await Deno.writeTextFile(
      new URL(file_name, import.meta.url),
      JSON.stringify(json_object, null, 2),
    );
    
    // Using tab to format
    await Deno.writeTextFile(
      new URL(file_name, import.meta.url),
      JSON.stringify(json_object, null, "\t"),
    );
    

    您可以在以下链接 https://doc.deno.land/builtin/stable 中阅读有关 Deno 内置函数的更多信息

    关于 JSON.stringify 这里https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/JSON/stringify

    【讨论】:

    • 感谢您的反馈,但我希望从 .env 文件中的环境变量中提取 json 对象部分。
    • 感谢您的反馈。我也给了你一个赞成票,比如添加 try/catch 并检查来自 .env 文件的输入是否有效。
    【解决方案3】:

    尝试await writePackageJsonFile(packageName, JSON.parse(packageContents));,并将contents: string 更改为contents: any,以便它接受一个对象(或重新创建对象结构并分配该类型)。

    【讨论】:

    • Deno 允许顶级等待权限(不需要在异步函数中)?
    • 啊,没关系,然后@Aaron,以前从未使用过 Deno。
    猜你喜欢
    • 2021-08-05
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-07-14
    • 2019-01-25
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多