Working with Data on the Web
Illustration by John Hersey

Parsing YAML with JavaScript


From:

Working with Data on the Web

with Joseph Lowery

Start your free trial now, and begin learning software, business and creative skills—anytime, anywhere—with video instruction from recognized industry experts.

Start Your Free Trial Now

Video: Parsing YAML with JavaScript

Let's say you've got a new client whose data is stored in a YAML format, and he wants to integrate that information in his or her website. I'm going to take you through the steps for doing just that in this lesson. If you went through the chapter four video on interacting with JavaScript for JSON, you'll see a lot of similarities. In fact, much of the same code applies. With index.htm from the Chapter 5/05-03 folder open, let me show you where we're going to insert our YAML powered html. We'll scroll down the page to around line 40 there, where we have the empty div with the id of container.
please wait ...
Watch the Online Video Course Working with Data on the Web
2h 21m Intermediate Aug 21, 2013

Viewers: in countries Watching now:

Often, designers need to convey simple data without the overhead of a relational database such as MySQL. This course introduces web technologies that make it easy for a designer or developer to store, retrieve, and display data online.

First, discover how data is collected via standard and advanced HTML5 forms. Then look at a client-friendly approach to storing that data using simple CSV files. Next, Joseph shows how to store, manage, and style data with the three big players: the granddaddy of static data, XML; the popular JavaScript-based JSON; and the recursively named YAML (YAML Ain't Markup Language), frequently used in Ruby-based projects. Plus, take a close look at basic HTML5 data options, including local storage and the flexible data attribute.

Topics include:
  • Interacting with data through HTML forms
  • Storing data as comma-separated values
  • Saving, retrieving, and displaying data as XML
  • Setting up and updating JSON data
  • Creating a YAML data file
  • Using HTML5 data storage solutions
Subjects:
Developer Web
Software:
HTML XML CSS JSON YAML
Author:
Joseph Lowery

Parsing YAML with JavaScript

Let's say you've got a new client whose data is stored in a YAML format, and he wants to integrate that information in his or her website. I'm going to take you through the steps for doing just that in this lesson. If you went through the chapter four video on interacting with JavaScript for JSON, you'll see a lot of similarities. In fact, much of the same code applies. With index.htm from the Chapter 5/05-03 folder open, let me show you where we're going to insert our YAML powered html. We'll scroll down the page to around line 40 there, where we have the empty div with the id of container.

We'll use this as our holder for the jquery inserted code. Unlike similar lessons on XML and JSON, you'll notice there is no loading gif. That's because jQuery has yet to incorporate YMAL into its AJAX model. Now, to parse YAML with JavaScript, we need to bring in a bit of a helping hand. A developer named Jeremy Favre has created a JavaScript library called YAML.js, which you can find on GitHub. With it, you'll able to easily load a YAML file as a JavaScript object.

I've already downloaded my copy of YAML.js and am ready to link to it via a script tag. So, I'm going to scroll back up in my code and lets put it right after the call out to jQuery. So, we'll enter in a script tag with a type equal text JavaScript and the source is going to be equal to a local copy of yaml.js. Close off that script tag, and then we'll go to the end of the line and make some space so we can start to build up our script tag. So, script, again type equals text/javascript, close off the tag. And now we're ready to add in the document ready function so that we can ensure that the rest of the page is fully loaded before we begin.

So, $ sign, document in parenthesis followed by .ready? And another set of parentheses, which contains function, parentheses. Now, after the parentheses following function, but before the final parentheses on that line, we want to put a pair of curly braces and then open it up so we can put our code inside there. Now, I'm going to go ahead and put my closing semicolon down at the bottom of the document-ready function. So, that's already taken care of.

As I mentioned, there's currently no way direct way to straightforwardly read in a YAML file with the .ajax method of jQuery. So, we're just going to load the file directly in using a YAML.js function, which is called YAML.load. So, I'll create a variable, var I'll call this yamlFile equals YAML all upper case, load and then parenthesis, what is it we want to load. We have a data file called data.yaml.

Put a semi colon on that, and let me just show you that datafile very quickly. Here it is where we have a master grouping of paintings and ended series of single paintings. Notice that I only have to define painting once unlike with XML, and then a simple hyphen allows me to group the various paintings. Okay, let's head back to our index.htm file. Now, it's time to loop through the loaded data using the .each function. Frankly, this code is almost verbatim the same as the code used for similar purpose with JSON data in the chapter 4 lesson titled Interacting with JavaScript.

If you've already done that work, feel free to copy and paste the code and make the single change necessary to get it to work. Of course, I'm still going to go through the code for YAML bit by bit starting with the each function itself. So, let's begin that $.each. Parenthesis. There are basically two arguments here, the first argument points to the portion of the yamlFile to loop through, which are the painting objects. So, to target that, we'll put in our variable, yamlFile and then the first element within that that we want to look at, which is the overall grouping of paintings.

the specific group that we want to look at painting. And if you have copied in that code that I mentioned from chapter 4, this is the one area that you need to change. Okay. After we've identified what it is that we want to do. Let's enter in our function call. And then in the parentheses it takes two arguments, one for keys, we'll give that a k. And one for values, v. And then after the kv, I'll put in a curly brace pair and again close it up with my semicolon.

Okay. Now, we really only need the values here, so we're going to set up three variables that access them. First is the title variable. And we'll look for v.title. Next is the image. And I'm just going to call this img and v.image will get us that information. And then price. Var price equals v price. Next, comes the append function, which integrates the HTML and data, we'll step through that very carefully.

Alright. So, lets start it off with a $ sign, identifying where we want this code to go, and we want it to go into that div that I showed you earlier with the id of container. And we're going to append some code to that. So .append. Open up a pair of parentheses and a set of single quotes. Within this first single quote is going to be a div with a class of painting and the beginning of our image tag. We'll start out with div, give it a class equal to and use double quotes here because we are within single quotes.

Now, after that closing double quote, close off the div tag and we're ready to start our image tag. So, bracket img and the first parameter is source. And again, we'll start that with our double quotes. Now, we're going to insert one of our variables right after we give the initial path. So, I don't need this closing double quote here, so I'm going to go ahead and erase that and, type in the path to where our images are stored.

And you'll be very surprised to hear that they're in a folder called Images. Now, let's go after the single quotes so that first part of HTML is done and we're ready to concatenate our variable, which is image. And another $ sign to go back to HTML so we'll start up again with single quotes and we need to close off that double quote so I'll enter it in. My code editor likes to put in pairs of double quotes, so I'm going to need to remove that second one.

And now we've got a couple more image parameters to enter, so the first is width and we'll set that to 200. The next one is height. And that is set to 225. You'll notice I'm having to remove the second of my double quotes every other time. It's just something to keep me on my toes here. So next up, we'll put in an attribute alt, so we have some alt text here. And the all text that we want to bring in, we're going to pull in dynamically from our YAML file, and this will be the title again.

So, open it up with a double quote, and now we're ready to move past the single quote, and concatenate in our title. And now back to HTML. Again, we're going to close off that double quote. Only one, thank you. And now, we're ready to finish up the image tag and we'll do that with a forward slash and a car/g. Okay. Right after the image is in, we'll use a linebreak br tag.

And then put the title in its own div with a class of titles. So, little more HTML to go here. br/ to close off our line break tag, and now let's create that div with the class equal to title. And after you close off the div with the class of title, that's the end of that little string of HTML and we'll just concatenate in title one more time so you can reuse your data as needed.

And now let's head back to a little bit of HTML. Another line break. And we're going to put in the price now. Now, the price, if we take a look at the data, you'll see that the price just has numbers here. So, since what we're dealing with dollars, we'll add in a $ sign. And that's the end of that little HTML string. So, let's concatenate in price plus price plus and here's our final bit of HTML closing off a couple of divs.

So, the first one will take care of the title div and then the second one will finish off the painting div. Alright. Our code is now complete let's save the file. And then go check it out in the browser. Let me refresh the page to load in our YAML data, and there it is! Should have four paintings, one two three four, each with their own title, each with the price. Nice! While YAML's integration into jQuery is not quite as robust as that of XML or JSON, its popularity is really growing.

And that might change in future updates to the framework.

There are currently no FAQs about Working with Data on the Web.

 
Share a link to this course

What are exercise files?

Exercise files are the same files the author uses in the course. Save time by downloading the author's files instead of setting up your own files, and learn by following along with the instructor.

Can I take this course without the exercise files?

Yes! If you decide you would like the exercise files later, you can upgrade to a premium account any time.

Become a member Download sample files See plans and pricing

Please wait... please wait ...
Upgrade to get access to exercise files.

Exercise files video

How to use exercise files.

Learn by watching, listening, and doing, Exercise files are the same files the author uses in the course, so you can download them and follow along Premium memberships include access to all exercise files in the library.


Exercise files

Exercise files video

How to use exercise files.

For additional information on downloading and using exercise files, watch our instructional video or read the instructions in the FAQ .

This course includes free exercise files, so you can practice while you watch the course. To access all the exercise files in our library, become a Premium Member.

* Estimated file size

Are you sure you want to mark all the videos in this course as unwatched?

This will not affect your course history, your reports, or your certificates of completion for this course.


Mark all as unwatched Cancel

Congratulations

You have completed Working with Data on the Web.

Return to your organization's learning portal to continue training, or close this page.


OK
Become a member to add this course to a playlist

Join today and get unlimited access to the entire library of video courses—and create as many playlists as you like.

Get started

Already a member ?

Exercise files

Learn by watching, listening, and doing! Exercise files are the same files the author uses in the course, so you can download them and follow along. Exercise files are available with all Premium memberships. Learn more

Get started

Already a Premium member?

Exercise files video

How to use exercise files.

Ask a question

Thanks for contacting us.
You’ll hear from our Customer Service team within 24 hours.

Please enter the text shown below:

The classic layout automatically defaults to the latest Flash Player.

To choose a different player, hold the cursor over your name at the top right of any lynda.com page and choose Site preferences from the dropdown menu.

Continue to classic layout Stay on new layout
Exercise files

Access exercise files from a button right under the course name.

Mark videos as unwatched

Remove icons showing you already watched videos if you want to start over.

Control your viewing experience

Make the video wide, narrow, full-screen, or pop the player out of the page into its own window.

Interactive transcripts

Click on text in the transcript to jump to that spot in the video. As the video plays, the relevant spot in the transcript will be highlighted.

Learn more, save more. Upgrade today!

Get our Annual Premium Membership at our best savings yet.

Upgrade to our Annual Premium Membership today and get even more value from your lynda.com subscription:

“In a way, I feel like you are rooting for me. Like you are really invested in my experience, and want me to get as much out of these courses as possible this is the best place to start on your journey to learning new material.”— Nadine H.

Thanks for signing up.

We’ll send you a confirmation email shortly.


Sign up and receive emails about lynda.com and our online training library:

Here’s our privacy policy with more details about how we handle your information.

Keep up with news, tips, and latest courses with emails from lynda.com.

Sign up and receive emails about lynda.com and our online training library:

Here’s our privacy policy with more details about how we handle your information.

   
submit Lightbox submit clicked
Terms and conditions of use

We've updated our terms and conditions (now called terms of service).Go
Review and accept our updated terms of service.