Skip to content
Tutorials Center
My learning

Topics

Lesson 39 of 39 ยท Projects and Practice

Practice: Data Format Exercises

Practice YAML quoting, CSV statistics, JSON Lines deduplication, Markdown link extraction and flat-to-nested conversion with five worked exercises, hints, runnable solutions and self-tests.

Reading about formats teaches you the rules; solving small problems makes them stick. This page has five exercises, one per theme of the chapters on YAML, CSV, JSON Lines, Markdown and conversion. Each has a task, a hint, and a runnable solution with self-tests that you can edit. The best way to use it: read the task, try writing your own function first (in the editor, replace the solution), and only then compare. All code runs in Node; assertions print ok or FAIL so you see immediately whether your version works.

Each solution uses a tiny check(name, actual, expected) helper that compares values as JSON.

Exercise 1: quote YAML scalars safely

Task. Write yamlScalar(value) that returns the YAML text for a string, adding double quotes only when needed: when it would be read as a boolean (true, false, yes, no, on, off, null, ~, any case), as a number (including leading zeros and 1.10), when it is empty, has leading or trailing spaces, contains : or #, or starts with one of - ? : , [ ] { } # & * ! | > ' " % @ or a backtick. Reuse JSON.stringify for quoting.

Hint. Combine several regular expressions into a list of "risky" tests. Review YAML Gotchas.

Node.js Exercise 1: yamlScalar

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or process.stdin), it gets the next line from this box.

Exercise 2: CSV statistics with quoted fields

Task. Given CSV text with a header item,qty,price, compute the total value (qty * price summed) and list the item names that contain a comma or a newline. Use a proper parser, not split(',').

Hint. Reuse the state machine from CSV Parsing and Its Pitfalls and convert strings with Number.

Node.js Exercise 2: CSV total and special names

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or process.stdin), it gets the next line from this box.

Exercise 3: deduplicate JSON Lines, keeping the latest

Task. A JSON Lines event stream may contain several records with the same id (updates). Write latestById(text) that returns the JSON Lines text with one line per id, keeping the last occurrence, ordered by the first time each id appeared. Skip blank and invalid lines.

Hint. A Map remembers insertion order; setting an existing key keeps its original position.

Node.js Exercise 3: latest record per id

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or process.stdin), it gets the next line from this box.

Task. Write extractLinks(markdown) returning an array of {text, url} for every inline link [text](url) that is not inside a fenced code block or an inline code span, and not an image (![alt](src)).

Hint. Remove fenced blocks line by line first, then strip inline code, then use a regular expression with a negative lookbehind for !.

Node.js Exercise 4: links outside code

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or process.stdin), it gets the next line from this box.

Exercise 5: a lossless round trip between flat and nested

Task. Write flatten(obj) and unflatten(flat) so that unflatten(flatten(x)) equals x for objects containing nested objects, arrays and scalars, including keys that contain a dot. Use a path separator that you escape: write \. for a literal dot in a key.

Hint. Flatten to an array of [pathParts, value] first; escape each part when joining; split on unescaped dots when reading back. Remember that arrays need markers so that [ 'a' ] does not become { "0": 'a' }. Here, encode array indices as [0] suffix parts.

Node.js Exercise 5: escaped-path round trip

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or process.stdin), it gets the next line from this box.

Self-review questions

Without running anything, try to answer these:

  1. A config value version: 3.10 loads as 3.1. Which YAML fix makes it stable in every parser?
  2. Why can a CSV record span more than one physical line, and how does that change a "count the lines" shortcut?
  3. Why is wc -l a valid record count for JSON Lines but not for CSV?
  4. Which part of a Markdown document must a link extractor ignore?
  5. Name two pieces of information a JSON-to-CSV conversion loses.

Answers: (1) quote it: version: "3.10"; (2) a quoted field may contain a newline, so you must parse quotes; (3) JSON Lines forbids raw newlines inside a record, so each record is exactly one line; (4) fenced code blocks and inline code spans; (5) types (everything becomes text) and structure (nesting and arrays).

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. Which Map behaviour made Exercise 3 simple?

    Overwriting a key's value leaves its position unchanged, so the order of first appearance is preserved while the value is the latest.
  2. 2. Why does Exercise 4 remove code before looking for links?

    A renderer does not treat text inside code as Markdown, so an extractor must skip it too.
  3. 3. Why must a lossless flatten escape dots in keys?

    The separator must be distinguishable from key content, or different structures flatten to the same paths.
  4. 4. What should yamlScalar do with the string 'NO'?

    Quoting keeps it a string in parsers that treat NO as a boolean.

Summary

  • Small exercises on each format reinforce the real rules: quoting, state machines, streaming, code-aware parsing and escaping.
  • Self-tests with a tiny check helper make solutions easy to verify.
  • Next steps: build the projects in this chapter, add features to them, and read the source of a real parser for one format you use daily.

Next: back to the track overview