YAML to JSON (to JS): the easy way!

I’ve recently found a ‘problem’ in my current project with configuration files when I’m trying to refactor some piece of code from PHP to Node.js.

More specifically, I’ve porting an image resizer because PHP library which was doing this job is currently deprecated and, instead of goes to another library, we decided to implement it again using Node.js

The problem was, that PHP library configuration is done using yaml and, our current solution uses a .js file to configure all formats of image resize.

Instead of rewriting all the configuration by hand, I took another approach.

This is how original file looked like:

Convert YAML to JSON

In this step, I used an online tool to convert yaml to a more JS friendly format: JSON.

We simply put our YAML in one box and the page shows us the output JSON. With this output, we open developer tools, and access to Console (or Source if you’re on chrome) and paste it, assigning to a variable:

Once you’ve loaded your data in a variable, you can manipulate to get your output result.

In my case, I also need to transform ‘a little’ the data to fit into my structure.

To do that, nothing better that filter and map methods.

In my case, I’m transforming from original data to an array of objects of the above type.

The last step is to get out of our data to a JS file. To do this, right click on the object from the console, and select “Copy Object”

Then, paste it into a new .js file and voilà! You’ve your JS file without rewriting it.

Links:

Desarrollador de software en @Hiberus. Java, JavaScript, Angular, Vue. Profesor en @Sanvalero. Papá de Ian y Zoe.

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store