Skip to content

Instantly share code, notes, and snippets.

@misshie
Created February 13, 2025 02:27
Show Gist options
  • Save misshie/81165eb5c4885d37b6331e52683f676a to your computer and use it in GitHub Desktop.
Save misshie/81165eb5c4885d37b6331e52683f676a to your computer and use it in GitHub Desktop.
OJ library's simple call-back handler to process JSON with duplicated keys
#!/usr/bin/env ruby
require 'oj'
class MyHandler
# see Oj::ScHandler
def hash_start ; {} ; end
def hash_end ; end
def array_start ; [] ; end
def array_end ; end
def add_value(value) ; value ; end
def array_append(array, value)
array << value
array
end
def hash_set(hash, key, value)
if hash.key?(key)
# 既に同じキーが存在する場合
if hash[key].is_a?(Array)
# すでに配列になっているなら、値を追加
hash[key] << value
else
# 配列でなければ、元の値と新しい値を配列に変換
hash[key] = [hash[key], value]
end
else
# キーが存在しない場合はそのままセット
hash[key] = value
end
hash
end
end
class Klass
TESTER = %!{"a": 1, "b": {"c": 2, "c": 3, "c":4}}!
# {"a"=>1, "b"=>{"c"=>[2, 3, 4]}}
def run
puts TESTER
pp Oj.sc_parse(MyHandler.new, TESTER)
end
end
if $0 == __FILE__
RubyVM::YJIT.enable if defined? RubyVM::YJIT.enable
Klass.new.run
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment