Link a YAML file with interfaces in JavaScript

I'm currently learning JavaScript and need to convert a YAML file to an Interface in JavaScript. Here is an example of the YAML file:

- provider_name: SEA-AD
  consortiumn_name: SEA-AD
  defaults: thumbnail
  Donors:
  - id: "https://portal.brain-map.org/explore/seattle-alzheimers-disease#Human-MTG-10x_SEA-AD_Male_TissueBlock"
    label: Registered 2/20/2023, Rebecca Hodge, SEA-AD
    description: "4 x 4 x 5 millimeter, 0.11 millimeter"
    link: "https://portal.brain-map.org/explore/seattle-alzheimers-disease"
    sex: Male
    Blocks: 
    - id: https://portal.brain-map.org/explore/seattle-alzheimers-disease#Human-MTG-10x_SEA-AD_Male_TissueBlock
      label: Registered 2/20/2023, Rebecca Hodge, SEA-AD

And here is the TypeScript interface:

export interface Provider {
    provider_name: string;
    provider_uuid: string;
    consortium_name: string;
    defaults: string;
    donors: Donor[]
}

export interface Donor {
    id: string;
    label: string;
    description: string;
    link: string;
    age: number;
    sex: string;
    bmi: number;
    blocks: Block[];
}

export interface Block {
    id: string;
    label: string;
}

Currently, I am struggling with mapping the inner variables like the "Donors" in the YAML file using JavaScript. Here is what I have tried so far:

cosnt data = load("YAML File");  
const provider = {
    provider_name: data.provider_name,
    consortium_name : data.consortium_name,
    dafaults: data.defaults,
    donors: data.Donors.map(function (donor) {

As someone new to JavaScript, I would appreciate any guidance on whether I am approaching this correctly or if there is a different method I should be using. The map function seems to be causing issues, as it is not available in JavaScript. Any suggestions or references would be highly valued. Thank you!

Answer №1

If you're looking to convert your yaml file into a JavaScript object, one option is to utilize libraries such as js-yaml. You can install it using the command: npm install js-yaml -g. To merge objects in this way:

var file1 = 'input1.yml',
    file2 = 'input2.yml',
    yaml = require('js-yaml'),
    fs = require('fs'),
    obj1 = yaml.load(fs.readFileSync(file1, {encoding: 'utf-8'}));
    obj2 = yaml.load(fs.readFileSync(file2, {encoding: 'utf-8'}));
    obj = { ...obj1, ...obj2 };

Keep in mind that these objects are already in JSON format.

Although this example isn't in TypeScript, it demonstrates the overall strategy.

Answer №2

To ensure that the loaded YAML is in the correct JSON format, you can utilize a tool like AJV for validation and data casting:

import Ajv, { JSONSchemaType } from "ajv"
const ajv = new Ajv()

interface Provider {
  provider_name: string;
}

const schema: JSONSchemaType<Provider> = {
  type: "object",
  properties: {
    provider_name: {type: "string"}
  },
  required: ["provider_name"]
}

const validate = ajv.compile(schema)

// Assuming YAML is parsed into a JSON Object
const data = load('file.yaml')

if (validate(data)) {
  // 'data' represents Provider at this point
  console.log(data.foo)
} else {
  console.log(validate.errors)
}

If preferred, you can simply cast it directly like so:

const data = load("YAML File") as Provider;  

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Tips for keeping the scrollbar permanently at the bottom in JavaScript?

I am trying to implement a feature where a div always scrolls down automatically. scrollDown(){ var chat = this.conversation; this.conversation.scrollTop = chat.scrollHeight; } checkKeyPress(e){ if (e.key == "Enter") { this.scrollDown(); .. ...

Using HTML and JavaScript to create a link that appears as a URL but actually directs to a JavaScript function

I am working on an HTML page and I am trying to create a link that appears to go to 'example.html' but actually goes to 'javascript:ajaxLoad(example.html);'. Here is what I have tried: <a href="example" onclick="javascipt:ajaxLoad( ...

Update the TypeScript definitions in the index.d.ts file using the npm command, by overriding it with the reference types

After running npm install, I noticed that the index.d.ts file contains a reference to the wrong path: /// <reference types="[WrongPath]"/>. As someone new to npm, TypeScript, and web development in general, I'm wondering if it's possible t ...

Troubleshooting: Inability to Use Type Assertions while Retrieving Data from

Struggling to retrieve and analyze complex data from Firebase for computation and Cloud Function execution. The format of the data is not aligning with my needs, as shown in this example: interface CourseEvent { coucourseGroupType: string; date: Fireb ...

Creating interactive comments in Vue 3 using dynamic rendering

Is there a way to properly display a dynamic comment in Vue 3? I attempted using v-html, but it's not working as expected in my scenario. Here is the example: <template> <!-- Method 1: not displaying correctly, https://i.sstatic.net/ddX39. ...

Connect guarantees while generating template

Fetching data through a function. Establishing a connection and retrieving necessary information. Some code has been omitted for brevity. function executeSQL(sql, bindParams , options) { return new Promise(function(resolve, reject) { ... resolv ...

What is the best way to retrieve data from MySQL for the current month using JavaScript?

I need to retrieve only the records from the current month within a table. Here is the code snippet: let startDate = req.body.startDate let endDate = req.body.endDate let result = await caseRegistration.findByDate({ p ...

Mongodb's adaptive criteria for email notifications

I am currently exploring methods to store conditions in mongodb for querying and validation purposes, followed by executing actions based on the outcome of the condition check. Let's begin with an illustration of the event object that I am contemplat ...

Issue: encountered an EADDRINUSE error stating that the address is already in use (8080) when attempting to run the script

After running the command npm ndb server.js, a debugging Chrome window appeared. However, I encountered some errors while trying to debug my code. When I clicked on "run script," another debugging Chrome window popped up and displayed these strange error ...

The setInterval function is malfunctioning

If I have the following function: function check(){ alert("Welcome"); } window.onload = check(); setInterval("check();", 5000); However, it is not working properly. Oddly enough, when I refresh the page, it works as intended. How can I resolve this i ...

Is it possible to adjust the width of the console window in Node.js?

Is it possible to adjust the Windows Console width using Node.js? process.stdout.columns =200; process.stdout.rows = 200; console.log(process.stdout.columns) console.log(process.stdout.rows) Why isn't it working as expected? ...

Tips for binding to a single input box within an ngFor loop

Can anyone lend a hand with some code? I'm working on a straightforward table using ngFor, but I'm facing an issue with input binding. The problem is that all the input fields generated by ngFor display the same value when typing. How can I preve ...

Implementing a JQuery function to generate a popup whenever a user clicks on a table row (tr) in an

I am working on a JSP page that contains a table, and I want to implement a pop-up window functionality when clicking on a specific row in the table. I have attempted to use JavaScript to connect with the row but so far, I have not been successful in creat ...

Steps for incorporating a type declaration for an array of objects in a React application with TypeScript

How can I specify the type for an array of objects in React using TypeScript? Here is the code snippet: const SomeComponent = (item: string, children: any) => { //some logic } In this code, you can see that I am currently using 'any' as ...

Tips on placing an li element into a designated DIV

Just starting out with jquery and working on a slider project. Here's what I have so far: <ul> <li> <img src="image.jpg"><p>description of the current image</p></li> <li> <img src="image.jpg"> ...

Conceal a specific class from being seen by another class of the same name upon clicking

I have a webpage with multiple images all sharing the same class name. When I try to hide a specific image by clicking on it, all images with that class are affected. Even though I used PHP to display the images on the webpage, I haven't been able to ...

Error in HTML5 video: Unable to access property '0' as it is undefined

I am trying to create a simple block displaying an HTML5 video tag. I want the ability to play different videos along with their titles from a JSON file by using previous and next buttons. Clicking the next button should play the next video, and the same g ...

svg icon hover effect not displaying color properly

Seeking expertise in incorporating social media icons with a hover effect to turn purple. Encountering an issue where the entire circle of the icon is mistakenly being painted on hover. Refer to the screenshot of the current outcome and desired result. Wo ...

Can InfluxDB be utilized to monitor and record customer usage data, such as servers and desktops?

Recently, I've delved into using InfluxDB to monitor my NodeJS application with Numbat, finding it to be quite convenient and straightforward to set up. However, I've been considering the idea of leveraging InfluxDB to track customer resource usa ...

Angular is used to call a function that captures a specific div and then waits for the capture to be completed before

I'm facing a challenge where I need to handle the capturing of a div using a method called capture() within another method. Take a look at the code snippet below: theimage; // declaring the variable callcapture() { // perform certain actions t ...