Module: ToonMyJson

Defined in:
lib/toon_my_json.rb,
lib/toon_my_json/decoder.rb,
lib/toon_my_json/encoder.rb,
lib/toon_my_json/version.rb

Overview

ToonMyJson provides bidirectional conversion between JSON and TOON format. TOON (Token-Oriented Object Notation) is a compact serialization format designed for LLMs that reduces token usage by 30-60% compared to JSON.

Defined Under Namespace

Classes: Decoder, Encoder, Error

Constant Summary collapse

VERSION =
'0.1.0'

Class Method Summary collapse

Class Method Details

.convert(input, **options) ⇒ Object

Alias for encode



36
37
38
# File 'lib/toon_my_json.rb', line 36

def self.convert(input, **options)
  encode(input, **options)
end

.decode(toon_string, **options) ⇒ Hash, ...

Convert TOON format string to Ruby object

Options Hash (**options):

  • :indent (Integer)

    Number of spaces per indentation level (default: 2)

  • :delimiter (String)

    Field delimiter for arrays (‘,’, ‘t’, or ‘|’) (default: ‘,’)

  • :json (Boolean)

    Return as JSON string instead of Ruby object (default: false)



48
49
50
51
52
# File 'lib/toon_my_json.rb', line 48

def self.decode(toon_string, **options)
  json_output = options.delete(:json)
  result = Decoder.new(**options).decode(toon_string)
  json_output ? JSON.pretty_generate(result) : result
end

.encode(input, **options) ⇒ String

Convert a Ruby object or JSON string to TOON format

Options Hash (**options):

  • :indent (Integer)

    Number of spaces per indentation level (default: 2)

  • :delimiter (String)

    Field delimiter for arrays (‘,’, ‘t’, or ‘|’) (default: ‘,’)

  • :length_marker (Boolean)

    Include array length markers (default: true)



22
23
24
25
26
27
28
29
30
31
32
33
# File 'lib/toon_my_json.rb', line 22

def self.encode(input, **options)
  data = if input.is_a?(String) && (input.start_with?('{', '[') || input.strip.start_with?('{', '['))
           begin
             JSON.parse(input)
           rescue JSON::ParserError
             input
           end
         else
           input
         end
  Encoder.new(**options).encode(data)
end