module TJSON

Tagged JSON with Rich Types

Constants

DuplicateNameError

Duplicate object name

EncodingError

Invalid string encoding

Error

Base class of all TJSON errors

MAX_NESTING

Maximum allowed nesting (TODO: use TJSON-specified maximum)

ParseError

Failure to parse TJSON document

TypeError

Invalid types

VERSION

Public Class Methods

generate(obj) click to toggle source

Generate TJSON from a Ruby Hash (TJSON only allows objects as toplevel values)

@param obj [Hash] Ruby Hash to serialize as TJSON @return [String] serialized TJSON

# File lib/tjson.rb, line 116
def self.generate(obj)
  raise TypeError, "toplevel type must be a Hash" unless obj.is_a?(Hash)
  JSON.generate(TJSON::DataType.encode(obj))
end
load(string)
Alias for: parse
load_file(filename) click to toggle source

Load data from a file containing TJSON

@param filename [String] name of the .tjson file @raise [TJSON::ParseError] an error occurred parsing the given file @return [Object] parsed data

# File lib/tjson.rb, line 108
def self.load_file(filename)
  load(File.read(filename))
end
parse(string) click to toggle source

Parse the given UTF-8 string as TJSON

@param string [String] TJSON string to be parsed @raise [TJSON::ParseError] an error occurred parsing the given TJSON @return [Object] parsed data

# File lib/tjson.rb, line 75
def self.parse(string)
  begin
    utf8_string = string.encode(Encoding::UTF_8)
  rescue ::EncodingError => ex
    raise TJSON::EncodingError, ex.message, ex.backtrace
  end

  begin
    object = ::JSON.parse(
      utf8_string,
      max_nesting:      MAX_NESTING,
      allow_nan:        false,
      symbolize_names:  false,
      create_additions: false,
      object_class:     TJSON::Object
    )
  rescue ::JSON::ParserError => ex
    raise TJSON::ParseError, ex.message, ex.backtrace
  end

  raise TJSON::TypeError, "invalid toplevel type: #{object.class}" unless object.is_a?(TJSON::Object)
  object
end
Also aliased as: load
pretty_generate(obj) click to toggle source

Generate TJSON from a Ruby Hash (TJSON only allows objects as toplevel values)

@param obj [Hash] Ruby Hash to serialize as TJSON @return [String] serialized TJSON

# File lib/tjson.rb, line 125
def self.pretty_generate(obj)
  raise TypeError, "toplevel type must be a Hash" unless obj.is_a?(Hash)
  JSON.pretty_generate(TJSON::DataType.encode(obj))
end