Try it yourself with our free Json Formatter tool — runs entirely in your browser, no signup needed.

How to Minify JSON in Ruby

How to Minify JSON in Ruby

Minifying JSON is an essential step in optimizing the performance of web applications that rely heavily on JSON data exchange. By removing unnecessary whitespace and formatting, minified JSON can significantly reduce the size of data transferred between the server and client, resulting in faster page loads and improved user experience. In this guide, we will explore how to minify JSON in Ruby.

Quick Example

Here is a minimal example of how to minify JSON in Ruby using the json gem:

require 'json'

def minify_json(json_string)
  JSON.parse(json_string).to_json
end

json_string = '{"name": "John", "age": 30, " occupation": "Developer"}'
minified_json = minify_json(json_string)
puts minified_json # Output: {"name":"John","age":30,"occupation":"Developer"}

This code defines a minify_json method that takes a JSON string as input, parses it into a Ruby hash using JSON.parse, and then converts it back to a JSON string using to_json. The resulting minified JSON string is then printed to the console.

Step-by-Step Breakdown

Let's break down the code line by line:

  1. require 'json': This line imports the json gem, which provides the JSON class and its methods for working with JSON data.
  2. def minify_json(json_string): This line defines a new method named minify_json that takes a single argument json_string.
  3. JSON.parse(json_string): This line parses the input JSON string into a Ruby hash using the JSON.parse method.
  4. .to_json: This line converts the parsed hash back to a JSON string using the to_json method.
  5. puts minified_json: This line prints the minified JSON string to the console.

Handling Edge Cases

Empty/Null Input

If the input JSON string is empty or null, the minify_json method will raise an error. To handle this edge case, we can add a simple check at the beginning of the method:

def minify_json(json_string)
  return '' if json_string.blank?
  JSON.parse(json_string).to_json
end

This code checks if the input string is blank (i.e., empty or null) using the blank? method, and returns an empty string if so.

Invalid Input

If the input JSON string is invalid, the JSON.parse method will raise a JSON::ParserError. To handle this edge case, we can add a rescue block to catch the error and return a meaningful error message:

def minify_json(json_string)
  begin
    JSON.parse(json_string).to_json
  rescue JSON::ParserError => e
    "Invalid JSON: #{e.message}"
  end
end

This code catches the JSON::ParserError exception and returns a string indicating that the input JSON is invalid.

Large Input

If the input JSON string is very large, the minify_json method may consume excessive memory. To handle this edge case, we can use a streaming JSON parser like json-stream:

require 'json/stream'

def minify_json(json_string)
  JsonStream.parse(json_string).to_json
end

This code uses the JsonStream class to parse the input JSON string in a streaming fashion, which can significantly reduce memory usage for large inputs.

Unicode/Special Characters

If the input JSON string contains Unicode or special characters, the minify_json method may not produce the expected output. To handle this edge case, we can use the json gem's built-in support for Unicode:

require 'json'

def minify_json(json_string)
  JSON.parse(json_string, symbolize_names: true).to_json
end

This code uses the symbolize_names option to enable Unicode support when parsing the input JSON string.

Common Mistakes

Mistake 1: Using JSON.pretty_generate

Using JSON.pretty_generate instead of to_json can produce a formatted JSON string with unnecessary whitespace:

def minify_json(json_string)
  JSON.parse(json_string).pretty_generate # Wrong!
end

Corrected code:

def minify_json(json_string)
  JSON.parse(json_string).to_json
end

Mistake 2: Not Handling Edge Cases

Failing to handle edge cases like empty/null input or invalid input can cause the minify_json method to raise errors or produce unexpected output:

def minify_json(json_string)
  JSON.parse(json_string).to_json # No error handling!
end

Corrected code:

def minify_json(json_string)
  return '' if json_string.blank?
  begin
    JSON.parse(json_string).to_json
  rescue JSON::ParserError => e
    "Invalid JSON: #{e.message}"
  end
end

Mistake 3: Using JSON.generate with Options

Using JSON.generate with options like :indent or :space can produce a formatted JSON string with unnecessary whitespace:

def minify_json(json_string)
  JSON.generate(JSON.parse(json_string), indent: 2) # Wrong!
end

Corrected code:

def minify_json(json_string)
  JSON.parse(json_string).to_json
end

Performance Tips

Tip 1: Use a Streaming JSON Parser

Using a streaming JSON parser like json-stream can significantly reduce memory usage for large inputs:

require 'json/stream'

def minify_json(json_string)
  JsonStream.parse(json_string).to_json
end

Tip 2: Avoid Using JSON.pretty_generate

Using JSON.pretty_generate can produce a formatted JSON string with unnecessary whitespace, which can increase the size of the output:

def minify_json(json_string)
  JSON.parse(json_string).to_json # Faster and more efficient
end

Tip 3: Use a JSON Minification Gem

Using a dedicated JSON minification gem like json-minifier can provide additional performance optimizations:

require 'json-minifier'

def minify_json(json_string)
  JsonMinifier.minify(json_string)
end

FAQ

Q: What is the difference between JSON.parse and JSON.load?

A: JSON.parse parses a JSON string into a Ruby hash, while JSON.load loads a JSON string into a Ruby object.

Q: How do I handle Unicode characters in my JSON input?

A: Use the symbolize_names option when parsing the input JSON string to enable Unicode support.

Q: What is the fastest way to minify JSON in Ruby?

A: Use a streaming JSON parser like json-stream and avoid using JSON.pretty_generate.

Q: Can I use JSON.minify to minify JSON?

A: No, JSON.minify is not a standard method in the json gem. Use to_json instead.

Q: How do I handle large JSON inputs?

A: Use a streaming JSON parser like json-stream to reduce memory usage.

AI agent tools available. The CodeTidy MCP Server gives Claude, Cursor, and other AI agents access to 60+ developer tools. One command: npx @codetidy/mcp