@@ -23,15 +23,28 @@ require "json"
23
23
require " json_scanner"
24
24
25
25
large_json = " [#{ " 4," * 100_000 } 42#{ " ,2" * 100_000 } ]"
26
- where_is_42 = JsonScanner .scan(large_json, [[100_000 ]], false ).first
26
+ where_is_42 = JsonScanner .scan(large_json, [[100_000 ]]).first
27
27
# => [[200001, 200003, :number]]
28
28
where_is_42.map do |begin_pos , end_pos , _type |
29
29
JSON .parse(large_json.byteslice(begin_pos...end_pos), quirks_mode: true )
30
30
end
31
31
# => [42]
32
32
33
+ # You can supply multiple paths to retrieve different values; each path can match multiple results,
34
+ # values may overlap if needed
35
+ question_path = [" data" , " question" ]
36
+ answers_path = [" data" , " answers" , (0 ..- 1 )]
37
+ json_str = ' {"data": {"question": "the Ultimate Question of Life, the Universe, and Everything", "answers": [42, 0, 420]}}'
38
+ questions_pos, answers_pos = JsonScanner .scan(json_str, [question_path, answers_path])
39
+ question_pos = questions_pos.first
40
+ question = JSON .parse(json_str.byteslice(question_pos[0 ]...question_pos[1 ]), quirks_mode: true )
41
+ # => "the Ultimate Question of Life, the Universe, and Everything"
42
+ answers = answers_pos.map { |begin_pos , end_pos , _type | JSON .parse(json_str.byteslice(begin_pos...end_pos), quirks_mode: true ) }
43
+ # => [42, 0, 420]
44
+
45
+ # Result contains byte offsets, you need to be careful when working with non-binary strings
33
46
emoji_json = ' {"grin": "😁", "heart": "😍", "rofl": "🤣"}'
34
- begin_pos, end_pos, = JsonScanner .scan(emoji_json, [[" heart" ]], false ).first.first
47
+ begin_pos, end_pos, = JsonScanner .scan(emoji_json, [[" heart" ]]).first.first
35
48
emoji_json.byteslice(begin_pos...end_pos)
36
49
# => "\"😍\""
37
50
# Note: You most likely don't need the `quirks_mode` option unless you are using an older version
73
86
``` ruby
74
87
JsonScanner .scan(' [0, 42, 0]' , [[(1 ..- 1 )]], with_path: true )
75
88
# => [[[[1], [4, 6, :number]], [[2], [8, 9, :number]]]]
89
+ # Or as a positional argument
90
+ JsonScanner .scan(' [0, 42, 0]' , [[(1 ..- 1 )]], true )
91
+ # => [[[[1], [4, 6, :number]], [[2], [8, 9, :number]]]]
76
92
JsonScanner .scan(' [0, 42],' , [[(1 ..- 1 )]], verbose_error: true )
77
93
# JsonScanner::ParseError (parse error: trailing garbage)
78
94
# [0, 42],
0 commit comments