在TypeScript中一一读取JSON数据

问题描述 投票:0回答:1

我使用 TypeScript/TestCafe 编写了一个 JSON 文件。

import fs = require("fs");

fixture`Create test data and pass them to the other tests`
  .page(url)
  .before(async (t) => {
    await createData();
  });

// Write data into a JSON file
async function createData() {
  var fname = 'Amanda';
  var lname = 'Hiddleston';
  let guardian = {
    firstName: fname,
    lastName: lname,
  };
  let data = JSON.stringify(guardian);
  fs.writeFileSync("data.json", data);
}

并且想要分别读取名字和姓氏。为此,我使用了这个方法:

interface MyObj {
  firstName: string;
  lastName: string;
}

var data = require("./data.json");
let obj: MyObj = JSON.parse(data);

test("Read first name from the JSON file", async (t) => {
  console.log(obj.firstName); // print first name
});

test("Read last name from the JSON file", async (t) => {
  console.log(obj.lastName); // print last name
});

但它显示行中存在错误

let obj: MyObj = JSON.parse(data)

请帮忙

typescript testing automated-tests e2e-testing testcafe
1个回答
1
投票

自定义类型防护是最简单的解决方案,通常足以进行外部数据验证:

// For example, you expect to parse a given value with `MyType` shape
type MyType = { name: string; description: string; }

// Validate this value with a custom type guard
function isMyType(o: any): o is MyType {
  return "name" in o && "description" in o
© www.soinside.com 2019 - 2024. All rights reserved.