~ubuntu-branches/ubuntu/trusty/ruby1.9/trusty

« back to all changes in this revision

Viewing changes to lib/json/common.rb

  • Committer: Bazaar Package Importer
  • Author(s): akira yamada
  • Date: 2007-06-06 11:58:24 UTC
  • mfrom: (1.1.7 upstream)
  • Revision ID: james.westby@ubuntu.com-20070606115824-qzldkdwq3dvfpf84
Tags: 1.9.0+20070606-1
* new upstream snapshot. (2006-06-06)
* updated debian/generated-incs/* files.

Show diffs side-by-side

added added

removed removed

Lines of Context:
 
1
require 'json/version'
 
2
 
 
3
module JSON
 
4
  class << self
 
5
    # If object is string like parse the string and return the parsed result as a
 
6
    # Ruby data structure. Otherwise generate a JSON text from the Ruby data
 
7
    # structure object and return it.
 
8
    def [](object)
 
9
      if object.respond_to? :to_str
 
10
        JSON.parse(object.to_str)
 
11
      else
 
12
        JSON.generate(object)
 
13
      end
 
14
    end
 
15
 
 
16
    # Returns the JSON parser class, that is used by JSON. This might be either
 
17
    # JSON::Ext::Parser or JSON::Pure::Parser.
 
18
    attr_reader :parser
 
19
 
 
20
    # Set the JSON parser class _parser_ to be used by JSON.
 
21
    def parser=(parser) # :nodoc:
 
22
      @parser = parser
 
23
      remove_const :Parser if const_defined? :Parser
 
24
      const_set :Parser, parser
 
25
    end
 
26
 
 
27
    # Return the constant located at _path_. The format of _path_ has to be
 
28
    # either ::A::B::C or A::B::C. In any case A has to be located at the top
 
29
    # level (absolute namespace path?). If there doesn't exist a constant at
 
30
    # the given path, an ArgumentError is raised.
 
31
    def deep_const_get(path) # :nodoc:
 
32
      path = path.to_s
 
33
      path.split(/::/).inject(Object) do |p, c|
 
34
        case
 
35
        when c.empty?             then p
 
36
        when p.const_defined?(c)  then p.const_get(c)
 
37
        else                      raise ArgumentError, "can't find const #{path}"
 
38
        end
 
39
      end
 
40
    end
 
41
 
 
42
    # Set the module _generator_ to be used by JSON.
 
43
    def generator=(generator) # :nodoc:
 
44
      @generator = generator
 
45
      generator_methods = generator::GeneratorMethods
 
46
      for const in generator_methods.constants
 
47
        klass = deep_const_get(const)
 
48
        modul = generator_methods.const_get(const)
 
49
        klass.class_eval do
 
50
          instance_methods(false).each do |m|
 
51
            m.to_s == 'to_json' and remove_method m
 
52
          end
 
53
          include modul
 
54
        end
 
55
      end
 
56
      self.state = generator::State
 
57
      const_set :State, self.state
 
58
    end
 
59
 
 
60
    # Returns the JSON generator modul, that is used by JSON. This might be
 
61
    # either JSON::Ext::Generator or JSON::Pure::Generator.
 
62
    attr_reader :generator
 
63
 
 
64
    # Returns the JSON generator state class, that is used by JSON. This might
 
65
    # be either JSON::Ext::Generator::State or JSON::Pure::Generator::State.
 
66
    attr_accessor :state
 
67
 
 
68
    # This is create identifier, that is used to decide, if the _json_create_
 
69
    # hook of a class should be called. It defaults to 'json_class'.
 
70
    attr_accessor :create_id
 
71
  end
 
72
  self.create_id = 'json_class'
 
73
 
 
74
  # The base exception for JSON errors.
 
75
  class JSONError < StandardError; end
 
76
 
 
77
  # This exception is raised, if a parser error occurs.
 
78
  class ParserError < JSONError; end
 
79
 
 
80
  # This exception is raised, if the nesting of parsed datastructures is too
 
81
  # deep.
 
82
  class NestingError < ParserError; end
 
83
 
 
84
  # This exception is raised, if a generator or unparser error occurs.
 
85
  class GeneratorError < JSONError; end
 
86
  # For backwards compatibility
 
87
  UnparserError = GeneratorError
 
88
 
 
89
  # If a circular data structure is encountered while unparsing
 
90
  # this exception is raised.
 
91
  class CircularDatastructure < GeneratorError; end
 
92
 
 
93
  # This exception is raised, if the required unicode support is missing on the
 
94
  # system. Usually this means, that the iconv library is not installed.
 
95
  class MissingUnicodeSupport < JSONError; end
 
96
 
 
97
  module_function
 
98
 
 
99
  # Parse the JSON string _source_ into a Ruby data structure and return it.
 
100
  #
 
101
  # _opts_ can have the following
 
102
  # keys:
 
103
  # * *max_nesting*: The maximum depth of nesting allowed in the parsed data
 
104
  #   structures. Disable depth checking with :max_nesting => false.
 
105
  def parse(source, opts = {})
 
106
    JSON.parser.new(source, opts).parse
 
107
  end
 
108
 
 
109
  # Unparse the Ruby data structure _obj_ into a single line JSON string and
 
110
  # return it. _state_ is a JSON::State object, that can be used to configure
 
111
  # the output further.
 
112
  #
 
113
  # It defaults to a state object, that creates the shortest possible JSON text
 
114
  # in one line and only checks for circular data structures. If you are sure,
 
115
  # that the objects don't contain any circles, you can set _state_ to nil, to
 
116
  # disable these checks in order to create the JSON text faster. See also
 
117
  # fast_generate.
 
118
  def generate(obj, state = JSON.state.new)
 
119
    obj.to_json(state)
 
120
  end
 
121
 
 
122
  alias unparse generate
 
123
  module_function :unparse
 
124
 
 
125
  # Unparse the Ruby data structure _obj_ into a single line JSON string and
 
126
  # return it. This method disables the checks for circles in Ruby objects.
 
127
  #
 
128
  # *WARNING*: Be careful not to pass any Ruby data structures with circles as
 
129
  # _obj_ argument, because this will cause JSON to go into an infinite loop.
 
130
  def fast_generate(obj)
 
131
    obj.to_json(nil)
 
132
  end
 
133
 
 
134
  alias fast_unparse fast_generate
 
135
  module_function :fast_unparse
 
136
 
 
137
  # Unparse the Ruby data structure _obj_ into a JSON string and return it. The
 
138
  # returned string is a prettier form of the string returned by #unparse.
 
139
  def pretty_generate(obj)
 
140
    state = JSON.state.new(
 
141
      :indent     => '  ',
 
142
      :space      => ' ',
 
143
      :object_nl  => "\n",
 
144
      :array_nl   => "\n",
 
145
      :check_circular => true
 
146
    )
 
147
    obj.to_json(state)
 
148
  end
 
149
 
 
150
  alias pretty_unparse pretty_generate
 
151
  module_function :pretty_unparse
 
152
end
 
153
 
 
154
module ::Kernel
 
155
  # Outputs _objs_ to STDOUT as JSON strings in the shortest form, that is in
 
156
  # one line.
 
157
  def j(*objs)
 
158
    objs.each do |obj|
 
159
      puts JSON::generate(obj)
 
160
    end
 
161
    nil
 
162
  end
 
163
 
 
164
  # Ouputs _objs_ to STDOUT as JSON strings in a pretty format, with
 
165
  # indentation and over many lines.
 
166
  def jj(*objs)
 
167
    objs.each do |obj|
 
168
      puts JSON::pretty_generate(obj)
 
169
    end
 
170
    nil
 
171
  end
 
172
 
 
173
  # If object is string like parse the string and return the parsed result as a
 
174
  # Ruby data structure. Otherwise generate a JSON text from the Ruby data
 
175
  # structure object and return it.
 
176
  def JSON(object)
 
177
    if object.respond_to? :to_str
 
178
      JSON.parse(object.to_str)
 
179
    else
 
180
      JSON.generate(object)
 
181
    end
 
182
  end
 
183
end
 
184
 
 
185
class ::Class
 
186
  # Returns true, if this class can be used to create an instance
 
187
  # from a serialised JSON string. The class has to implement a class
 
188
  # method _json_create_ that expects a hash as first parameter, which includes
 
189
  # the required data.
 
190
  def json_creatable?
 
191
    respond_to?(:json_create)
 
192
  end
 
193
end
 
194
  # vim: set et sw=2 ts=2: