-
Notifications
You must be signed in to change notification settings - Fork 1.2k
/
json.rb
65 lines (55 loc) · 1.31 KB
/
json.rb
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
require 'json'
require_relative 'json/builder'
require_relative 'json/error_handler'
require_relative 'json/handler'
require_relative 'json/parser'
module Aws
# @api private
module Json
class ParseError < StandardError
def initialize(error)
@error = error
super(error.message)
end
attr_reader :error
end
class << self
def load(json)
ENGINE.load(json, *ENGINE_LOAD_OPTIONS)
rescue *ENGINE_ERRORS => e
raise ParseError, e
end
def load_file(path)
load(File.open(path, 'r', encoding: 'UTF-8', &:read))
end
def dump(value)
ENGINE.dump(value, *ENGINE_DUMP_OPTIONS)
end
private
def oj_engine
require 'oj'
[
Oj,
[{ mode: :compat, symbol_keys: false }],
[{ mode: :compat }],
oj_parse_error
]
rescue LoadError
false
end
def json_engine
[JSON, [], [], [JSON::ParserError]]
end
def oj_parse_error
if Oj.const_defined?('ParseError')
[Oj::ParseError, EncodingError, JSON::ParserError]
else
[SyntaxError]
end
end
end
# @api private
ENGINE, ENGINE_LOAD_OPTIONS, ENGINE_DUMP_OPTIONS, ENGINE_ERRORS =
oj_engine || json_engine
end
end