Class: JSON5::Stringifier

Inherits:
Object
  • Object
show all
Defined in:
lib/json5/stringifier.rb

Instance Method Summary collapse

Constructor Details

#initialize(obj, replacer, space) ⇒ Stringifier

JSON5.stringify = function (obj, replacer, space)



5
6
7
8
9
# File 'lib/json5/stringifier.rb', line 5

def initialize obj, replacer, space
  if (replacer && (typeof(replacer) != "function" && !isArray(replacer)))
    throw new Error('Replacer must be a function or an array')
  end
end

Instance Method Details

#getReplacedValueOrUndefined(holder, key, isTopLevel) ⇒ Object



11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
# File 'lib/json5/stringifier.rb', line 11

def getReplacedValueOrUndefined holder, key, isTopLevel
  value = holder[key]

  # Replace the value with its toJSON value first, if possible
  # if (value && value.toJSON && typeof value.toJSON === "function")
  if (value && value.responds_to?(:to_json))
      # value = value.toJSON
      value = value.to_json
  end

  # If the user-supplied replacer if a function, call it. If it's an array, check objects' string keys for
  # presence in the array (removing the key/value pair from the resulting JSON if the key is missing).
  if (typeof(replacer) === "function")
      return replacer.call(holder, key, value)
  elsif(replacer)
      if (isTopLevel || isArray(holder) || replacer.indexOf(key) >= 0)
          return value
      else
          return undefined
      end
  else
      return value
  end
end

#isArray(obj) ⇒ Object

# polyfills



70
71
72
73
74
75
76
# File 'lib/json5/stringifier.rb', line 70

def isArray(obj)
  if (Array.isArray)
      return Array.isArray(obj)
  else
      return Object.prototype.toString.call(obj) === '[object Array]'
  end
end

#isDate(obj) ⇒ Object



78
79
80
# File 'lib/json5/stringifier.rb', line 78

def isDate(obj)
  return Object.prototype.toString.call(obj) === '[object Date]'
end

#isWord(key) ⇒ Object



49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
# File 'lib/json5/stringifier.rb', line 49

def isWord(key)
  if (typeof key != 'string')
      return false
  end
  if (!isWordStart(key[0]))
      return false
  end
  i = 1, length = key.length
  while (i < length) do
      if (!isWordChar(key[i]))
          return false
      end
      i += 1
  end
  return true
end

#isWordChar(char) ⇒ Object



36
37
38
39
40
41
# File 'lib/json5/stringifier.rb', line 36

def isWordChar(char)
  return (char >= 'a' && char <= 'z') ||
      (char >= 'A' && char <= 'Z') ||
      (char >= '0' && char <= '9') ||
      char === '_' || char === '$'
end

#isWordStart(char) ⇒ Object



43
44
45
46
47
# File 'lib/json5/stringifier.rb', line 43

def isWordStart(char)
  return (char >= 'a' && char <= 'z') ||
      (char >= 'A' && char <= 'Z') ||
      char === '_' || char === '$'
end