Top Related Projects
Parsing gigabytes of JSON per second : used by Facebook/Meta Velox, the Node.js runtime, ClickHouse, WatermelonDB, Apache Doris, Milvus, StarRocks
A fast JSON parser/generator for C++ with both SAX/DOM style API
JSON for Modern C++
C/C++ JSON parser/generator benchmark
Quick Overview
Oj is a fast JSON parser and Object marshaller for Ruby. It aims to be the fastest JSON parser and marshaller for Ruby, offering various parsing modes and optimizations to achieve high performance.
Pros
- Extremely fast JSON parsing and generation compared to other Ruby JSON libraries
- Multiple parsing modes to suit different needs (strict, compat, null, etc.)
- Supports both MRI Ruby and JRuby
- Extensive configuration options for fine-tuning performance and behavior
Cons
- May have compatibility issues with some Ruby gems due to its optimizations
- Learning curve for advanced features and configuration options
- Occasional discrepancies in behavior compared to the standard JSON library
- Limited support for some less common JSON features in certain modes
Code Examples
Parsing JSON:
require 'oj'
json_string = '{"name":"John","age":30,"city":"New York"}'
parsed_data = Oj.load(json_string)
puts parsed_data['name'] # Output: John
Generating JSON:
require 'oj'
data = { name: "Alice", age: 25, hobbies: ["reading", "swimming"] }
json_string = Oj.dump(data)
puts json_string
# Output: {"name":"Alice","age":25,"hobbies":["reading","swimming"]}
Using different parsing modes:
require 'oj'
json_string = '{"key": null}'
# Strict mode (raises an exception for null)
begin
Oj.load(json_string, mode: :strict)
rescue Oj::ParseError => e
puts "Strict mode error: #{e.message}"
end
# Compat mode (behaves like JSON.parse)
result = Oj.load(json_string, mode: :compat)
puts "Compat mode result: #{result.inspect}"
Getting Started
To use Oj in your Ruby project:
-
Install the gem:
gem install oj
-
In your Ruby file, require Oj:
require 'oj'
-
Use Oj for parsing or generating JSON:
# Parsing JSON parsed_data = Oj.load('{"key":"value"}') # Generating JSON json_string = Oj.dump({key: "value"})
For more advanced usage and configuration options, refer to the Oj documentation.
Competitor Comparisons
Parsing gigabytes of JSON per second : used by Facebook/Meta Velox, the Node.js runtime, ClickHouse, WatermelonDB, Apache Doris, Milvus, StarRocks
Pros of simdjson
- Extremely fast JSON parsing, leveraging SIMD instructions
- Language-agnostic C++ implementation with bindings for multiple languages
- Designed for handling large JSON files efficiently
Cons of simdjson
- Focused solely on JSON parsing, lacking serialization capabilities
- May have a steeper learning curve for integration compared to OJ
- Limited to JSON-specific operations
Code Comparison
simdjson:
#include "simdjson.h"
using namespace simdjson;
ondemand::parser parser;
auto json = padded_string::load("large.json");
ondemand::document doc = parser.iterate(json);
OJ:
require 'oj'
json = File.read('large.json')
parsed = Oj.load(json)
Key Differences
- simdjson is primarily a C++ library with a focus on high-performance JSON parsing
- OJ is a Ruby-specific gem that offers both parsing and serialization
- simdjson excels at handling large JSON files with minimal memory usage
- OJ provides a more comprehensive JSON toolkit for Ruby developers
- simdjson's performance benefits are most noticeable with larger JSON payloads
- OJ offers easier integration and a wider range of features for Ruby projects
A fast JSON parser/generator for C++ with both SAX/DOM style API
Pros of rapidjson
- Supports both SAX and DOM parsing styles, offering more flexibility
- Generally faster performance, especially for parsing large JSON documents
- More extensive documentation and examples available
Cons of rapidjson
- Larger codebase and more complex API, potentially steeper learning curve
- C++ only, while oj supports both C and Ruby
Code Comparison
oj (Ruby):
require 'oj'
json = Oj.dump({ foo: 'bar' })
parsed = Oj.load(json)
rapidjson (C++):
#include "rapidjson/document.h"
#include "rapidjson/writer.h"
#include "rapidjson/stringbuffer.h"
rapidjson::Document d;
d.SetObject();
d.AddMember("foo", "bar", d.GetAllocator());
rapidjson::StringBuffer buffer;
rapidjson::Writer<rapidjson::StringBuffer> writer(buffer);
d.Accept(writer);
std::string json = buffer.GetString();
Summary
rapidjson offers more features and better performance for C++ projects, while oj provides a simpler API and Ruby support. The choice between them depends on the specific project requirements, language preferences, and performance needs.
JSON for Modern C++
Pros of json
- Header-only library, easy to integrate into C++ projects
- Extensive documentation and examples
- Wide range of JSON manipulation features, including JSON Pointer and JSON Patch
Cons of json
- Slower parsing and serialization compared to oj
- Higher memory usage, especially for large JSON documents
- Steeper learning curve for advanced features
Code Comparison
json:
#include <nlohmann/json.hpp>
using json = nlohmann::json;
json j = {
{"name", "John"},
{"age", 30},
{"city", "New York"}
};
std::string s = j.dump();
oj:
#include "oj.h"
const char *json = "{\"name\":\"John\",\"age\":30,\"city\":\"New York\"}";
Val val = oj_parse(json, strlen(json));
char *s = oj_write_val(val, OJ_INDENT);
json offers a more C++-centric approach with modern language features, while oj provides a C-based interface with a focus on performance. json's syntax is more intuitive for C++ developers, but oj's simplicity can be advantageous in certain scenarios. The choice between the two depends on specific project requirements, performance needs, and developer preferences.
C/C++ JSON parser/generator benchmark
Pros of nativejson-benchmark
- Comprehensive benchmarking of multiple JSON libraries across different languages
- Provides detailed performance metrics and comparisons
- Useful for developers choosing a JSON library based on performance needs
Cons of nativejson-benchmark
- Not a JSON library itself, only a benchmarking tool
- May not reflect real-world performance in specific use cases
- Requires more setup and configuration to run benchmarks
Code Comparison
nativejson-benchmark (C++):
void ParseDouble(Benchmark& b) {
char buffer[32];
double d = 1.2345678;
int length = sprintf(buffer, "%g", d);
b.Run([&]() {
return std::stod(buffer);
});
}
oj (Ruby):
def parse_double(str)
Oj.load(str)
end
str = '1.2345678'
parse_double(str)
Summary
nativejson-benchmark is a comprehensive benchmarking tool for JSON libraries, while oj is a high-performance JSON parser for Ruby. nativejson-benchmark offers broader language support and detailed metrics, but oj provides a ready-to-use JSON parsing solution for Ruby developers. The choice between them depends on whether you need benchmarking capabilities or a specific JSON library for Ruby.
Convert designs to code with AI
Introducing Visual Copilot: A new AI model to turn Figma designs to high quality code using your components.
Try Visual CopilotREADME
gem
A fast JSON parser and Object marshaller as a Ruby gem.
Version 3.13 is out with a much faster parser (Oj::Parser
) and option isolation.
Using
require 'oj'
h = { 'one' => 1, 'array' => [ true, false ] }
json = Oj.dump(h)
# json =
# {
# "one":1,
# "array":[
# true,
# false
# ]
# }
h2 = Oj.load(json)
puts "Same? #{h == h2}"
# true
Installation
gem install oj
or in Bundler:
gem 'oj'
Rails and json quickstart
See the Quickstart sections of the Rails and json docs.
multi_json
Code which uses multi_json will automatically prefer Oj if it is installed.
Support
Get supported Oj with a Tidelift Subscription. Security updates are supported.
Further Reading
For more details on options, modes, advanced features, and more follow these links.
- {file:Options.md} for parse and dump options.
- {file:Modes.md} for details on modes for strict JSON compliance, mimicking the JSON gem, and mimicking Rails and ActiveSupport behavior.
- {file:JsonGem.md} includes more details on json gem compatibility and use.
- {file:Rails.md} includes more details on Rails and ActiveSupport compatibility and use.
- {file:Custom.md} includes more details on Custom mode.
- {file:Encoding.md} describes the :object encoding format.
- {file:Compatibility.md} lists current compatibility with Rubys and Rails.
- {file:Advanced.md} for fast parser and marshalling features.
- {file:Security.md} for security considerations.
- {file:InstallOptions.md} for install option.
Releases
See {file:CHANGELOG.md} and {file:RELEASE_NOTES.md}
Links
-
Documentation: http://www.ohler.com/oj/doc, http://rubydoc.info/gems/oj
-
GitHub repo: https://github.com/ohler55/oj
-
RubyGems repo: https://rubygems.org/gems/oj
Follow @peterohler on Twitter for announcements and news about the Oj gem.
Performance Comparisons
-
Oj Strict Mode Performance compares Oj strict mode parser performance to other JSON parsers.
-
Oj Compat Mode Performance compares Oj compat mode parser performance to other JSON parsers.
-
Oj Object Mode Performance compares Oj object mode parser performance to other marshallers.
-
Oj Callback Performance compares Oj callback parser performance to other JSON parsers.
Links of Interest
-
Fast XML parser and marshaller on RubyGems: https://rubygems.org/gems/ox
-
Fast XML parser and marshaller on GitHub: https://github.com/ohler55/ox
-
Need for Speed for an overview of how Oj::Doc was designed.
-
OjC, a C JSON parser: https://www.ohler.com/ojc also at https://github.com/ohler55/ojc
-
Agoo, a high performance Ruby web server supporting GraphQL on GitHub: https://github.com/ohler55/agoo
-
Agoo-C, a high performance C web server supporting GraphQL on GitHub: https://github.com/ohler55/agoo-c
-
oj-introspect, an example of creating an Oj parser extension in C: https://github.com/meinac/oj-introspect
Contributing
- Provide a Pull Request off the
develop
branch. - Report a bug
- Suggest an idea
- Code is now formatted with the clang-format tool with the configuration file in the root of the repo.
Top Related Projects
Parsing gigabytes of JSON per second : used by Facebook/Meta Velox, the Node.js runtime, ClickHouse, WatermelonDB, Apache Doris, Milvus, StarRocks
A fast JSON parser/generator for C++ with both SAX/DOM style API
JSON for Modern C++
C/C++ JSON parser/generator benchmark
Convert designs to code with AI
Introducing Visual Copilot: A new AI model to turn Figma designs to high quality code using your components.
Try Visual Copilot