-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathhash_streamer.rb
executable file
·61 lines (51 loc) · 1.27 KB
/
hash_streamer.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
#!/usr/bin/env ruby
require 'oj'
require 'json'
# This is a custom handler for Oj that will stream a JSON object to a processor
# as it is parsed. This is useful for large JSON objects that you don't want to
# load into memory all at once.
#
# Usage:
# jsonio = File.open('customers-hash.json', 'r')
# processor = proc { |result| p result }
# Oj.sc_parse(HashHandler.new(processor), jsonio)
#
# The processor will be called with each hash object in the JSON file.
#
# Note: This is a very basic example and does not handle all JSON types.
# For a more complete example, see the Oj::ScHandler documentation.
# https://www.rubydoc.info/gems/oj/Oj/ScHandler
class HashHandler < ::Oj::ScHandler
def initialize(processor)
@processor = processor
@hash_depth = 0
end
def hash_start
@hash_depth += 1
{}
end
def hash_set(h,k,v)
if @hash_depth == 1
@processor.call(k => v)
else
h[k] = v
end
end
def hash_end
@hash_depth -= 1
end
def array_start
[]
end
def array_append(a,v)
a << v
end
def error(message, line, column)
p "ERROR: #{message}"
end
end
if __FILE__ == $0
jsonio = File.open('customers-hash.json', 'r')
processor = proc { |result| p result }
Oj.sc_parse(HashHandler.new(processor), jsonio)
end