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

Utilize CSS properties to pass as arguments to a JavaScript function

Is there a way for me to make my CSS animation functions more efficient? I have similar functions for different properties like height, width, and left. Can I modify the function below to accept a CSS property argument instead of hardcoding height? Window ...

Having trouble incorporating @types/pdfmake into an Angular project

I have been experimenting with integrating a JS library called pdfmake into an Angular application. I found some guidance on how to accomplish this at https://www.freecodecamp.org/news/how-to-use-javascript-libraries-in-angular-2-apps/, which involved usin ...

Authorize a user through Loopback using REST as the data source

I am currently working with a UserModel that is based on the USER model and uses a REST datasource. "UserModel": { "dataSource": "mock", "public": true } Data Source Configuration "mock": { "name": "mock", "baseURL": "http://localhost:3000/", "connector ...

Steps for integrating a Facebook Messenger chatbot with a MongoDB database in order to submit requests and retrieve responses through conversations with the bot

I am currently working on integrating my Facebook Messenger chatbot with a MongoDB database. The chatbot I have created is a simple questionnaire chatbot that takes text inputs and displays buttons with options. When a user clicks on a button, it should ...

The Datatable plugin is unable to effectively customize tables that are loaded dynamically

Within my single page application, the home page initially loads all static resources and js files. Subsequently, upon a user click event, the table is dynamically loaded. Unfortunately, the datatable customization does not seem to be applied on the newly ...

Is there a way to prevent users from right clicking on all links with the same class using js/jquery?

Rails 4 + JS + jquery Is there a way to disable right click on links with the same class in Rails? <% @schedule_hash.values.each do |schedule| %> <%= link_to "Cancellation policy", {:controller => 'web', :action => 'get ...

Tips for updating the content within an HTML tag with jQuery

I am looking to update the parameter value of an applet tag based on the selection from a dropdown menu. As I am new to jQuery, I would appreciate any guidance on how to achieve this using jQuery. This is my current applet code: <applet id="decisiontr ...

React web app experiencing an issue with MUI Drawer opening flawlessly but failing to close

Recently, I encountered an issue with my React app. I have a Navbar component that displays a Sidebar component when the screen is small, using Material UI for the Drawer functionality. The problem arises when clicking the hamburger icon to open the drawe ...

Associating checkbox options with an array that is void of elements

I have a series of arrays linked to checkboxes and I am trying to create a unique array based on the selected checkbox values. Here is an example of the HTML structure: <input type="checkbox" value="value1">Value 1 <input type="checkbox" value=" ...

How to effectively compare time duration with a timer in the Laravel framework

I am managing a table that stores various job entries for employees. Each job entry includes a column for duration. I would like to trigger an alert or other event when the duration of a job has ended. My project is built using Laravel and VueJS. Below i ...

Extracting data from web pages using JavaScript and PHP

Using the following script, I am able to scrape all the items from this specific page: $html = file_get_contents($list_url); $doc = new DOMDocument(); libxml_use_internal_errors(TRUE); if(!empty($html)) { $doc->loadHTML($html); ...

Encode JavaScript field without affecting the appearance

I need to encode a specific search field before submitting it as a $_GET request. To do this, I am using the encodeURIComponent() function on that field before the form is submitted. $('#frmMainSearch').submit(function() { var field = $(this ...

"Setting Up a Service in Angular: A Step-by-Step Guide

I am facing an issue with a root service that contains composition within it, as shown below: import { Injectable } from '@angular/core'; @Injectable({ providedIn: 'root', }) export class MapService { private rmap: RMap; ini ...

Maintain original image file name when downloading

I have successfully created a download link containing a base 64 encoded image. The only issue is that I need to retain the original file name, which is dynamic and cannot be hardcoded. downloadImage: function(){ var image_url = document.getEleme ...

Frequent 502 bad gateway issue arising intermittently on server configuration with nginx, nodejs, and mongodb stack

We are currently using nodejs(v 0.10.29), express, nginx(version 1.4.6) with mongodb(v 2.6.3) replicaset and encountering sporadic 502 bad gateway errors. Although pm2 logs fail to capture the error, nginx's error.log is indicating: recv() failed (10 ...

Create a new visual masterpiece using Canvas by repurposing an

I am currently working on the following code snippet; export default async function draw(elRef : RefObject<HTMLCanvasElement>, tileData : TileProps) { const canvas = elRef.current!; const ctx = canvas.getContext('2d')!; ctx.clearRect( ...

Is combining Nuxt 3 with WP REST API, Pinia, and local storage an effective approach for user authentication?

My current project involves utilizing NUXT 3 for the frontend and integrating Wordpress as the backend. The data is transmitted from the backend to the frontend through the REST API. The application functions as a content management system (CMS), with all ...

Accessing audio files in a directory using ajax

I need assistance with implementing a feature in my mp3 music player code. I want the player to fetch songs from a directory instead of using the page's URL. var songs = [{ { title: 'Blackout City', artist: 'Anamanaguchi&ap ...

The express error middleware is failing to properly handle errors that are being thrown from the promise's

When I throw an Error, express will render it nicely using the connected errorHandler middleware. exports.list = function(req, res){ throw new Error('asdf'); res.send("We don't reach this point because the Error is thrown synchronously" ...

Is it possible for me to route a URL to a particular content generated by Ajax on a separate webpage?

I appreciate anyone taking the time to help with this, especially since I already had to get 12 stitches. Here's what I'm dealing with: mysite.com/documentation - page with a menu and content section (content will load dynamically via Ajax w ...