Anupama Balasooriya
Anupama Balasooriya

Reputation: 31

Read JSON data one by one in TypeScript

I have written a JSON file using TypeScript/TestCafe.

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);
}

And want to read firstName and LastName separately. For that, I used this method:

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
});

But it shows an error in the line let obj: MyObj = JSON.parse(data).

Please help

Upvotes: 0

Views: 1291

Answers (1)

Quickk Care
Quickk Care

Reputation: 51

Custom type guards are the simplest solution and often sufficient for external data validation:

// 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

Upvotes: 1

Related Questions