Chapter 17: JSON Handling in Ruby

Parse, validate, and send JSON responses. In this chapter, you will learn json handling in depth with Ruby code examples, explanations, and best practices.

Overview

This chapter covers json handling for Kungfu.js developers using Ruby. We will start with the basics, move through practical examples, and end with advanced techniques and common pitfalls.

Why This Matters

Understanding json handling is essential because it is a core part of building web applications. Every real-world app needs to handle parse, validate, and send json responses. Skipping this chapter would leave a gap in your knowledge that would cause problems later.

Code Example

Here is how to handle requests and responses in Ruby:

// Parse JSON body
app.post('/api/users', (req) => {
    const body = JSON.parse(req.body);
    const name = body.name;
    const email = body.email;
    
    return {
        status: 201,
        body: JSON.stringify({ id: 1, name, email })
    };
});

// Send JSON response
app.get('/api/users', (req) => {
    return {
        status: 200,
        headers: { 'content-type': 'application/json' },
        body: JSON.stringify([{ id: 1, name: 'Alice' }])
    };
});

Common Mistakes

  • Not reading the documentation: Always check the API reference when something does not work as expected.
  • Skipping security: Never disable the default middleware unless you have a very good reason. Security is not optional.
  • Not testing: Write tests for your handlers. Kungfu.js makes this easy with the built-in test utilities.

Summary

In this chapter, you learned about json handling in Ruby. You saw code examples, understood how things work under the hood, and learned about common mistakes to avoid.

What is Next?

In chapter 18, we will cover Form Data: Handle URL-encoded form submissions.