Skip to content

Commit 171af2b

Browse files
committed
more examples in the README
1 parent cc5694b commit 171af2b

File tree

1 file changed

+18
-2
lines changed

1 file changed

+18
-2
lines changed

README.md

Lines changed: 18 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -23,15 +23,28 @@ require "json"
2323
require "json_scanner"
2424

2525
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
2727
# => [[200001, 200003, :number]]
2828
where_is_42.map do |begin_pos, end_pos, _type|
2929
JSON.parse(large_json.byteslice(begin_pos...end_pos), quirks_mode: true)
3030
end
3131
# => [42]
3232

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
3346
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
3548
emoji_json.byteslice(begin_pos...end_pos)
3649
# => "\"😍\""
3750
# Note: You most likely don't need the `quirks_mode` option unless you are using an older version
@@ -73,6 +86,9 @@ end
7386
```ruby
7487
JsonScanner.scan('[0, 42, 0]', [[(1..-1)]], with_path: true)
7588
# => [[[[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]]]]
7692
JsonScanner.scan('[0, 42],', [[(1..-1)]], verbose_error: true)
7793
# JsonScanner::ParseError (parse error: trailing garbage)
7894
# [0, 42],

0 commit comments

Comments
 (0)