Skip to content

Commit

Permalink
parser_json: use JSON.parse instead of .load (#4817)
Browse files Browse the repository at this point in the history
**Which issue(s) this PR fixes**: 
Fixes #

**What this PR does / why we need it**: 
Ref. #4813 (comment)
Fix wrong usage of `JSON.load` method.
We should use `JSON.parse` instead.

JSON.load performs unnecessary deserialisation.

```
irb(main):001> JSON.load('{ "json_class": "String", "raw": [72, 101, 108, 108, 111] }')
=> "Hello"
irb(main):002> JSON.parse('{ "json_class": "String", "raw": [72, 101, 108, 108, 111] }')
=> {"json_class" => "String", "raw" => [72, 101, 108, 108, 111]}
```


**Docs Changes**:

**Release Note**:

Signed-off-by: Shizuo Fujita <[email protected]>
  • Loading branch information
Watson1978 authored Feb 4, 2025
1 parent 1d5b0de commit 4f91c7f
Show file tree
Hide file tree
Showing 3 changed files with 4 additions and 4 deletions.
2 changes: 1 addition & 1 deletion lib/fluent/plugin/parser_json.rb
Original file line number Diff line number Diff line change
Expand Up @@ -54,7 +54,7 @@ def configure_json_parser(name)

log&.info "Oj is not installed, and failing back to JSON for json parser"
configure_json_parser(:json)
when :json then [JSON.method(:load), JSON::ParserError]
when :json then [JSON.method(:parse), JSON::ParserError]
when :yajl then [Yajl.method(:load), Yajl::ParseError]
else
raise "BUG: unknown json parser specified: #{name}"
Expand Down
2 changes: 1 addition & 1 deletion test/log/test_console_adapter.rb
Original file line number Diff line number Diff line change
Expand Up @@ -73,7 +73,7 @@ def test_args(level)
def test_options(level)
@console_logger.send(level, "subject", kwarg1: "opt1", kwarg2: "opt2")
lines = @logdev.logs[0].split("\n")
args = JSON.load(lines[1..].collect { |str| str.sub(/\s+\|/, "") }.join("\n"));
args = JSON.parse(lines[1..].collect { |str| str.sub(/\s+\|/, "") }.join("\n"));
assert_equal([
1,
"#{@timestamp_str} [#{level}]: 0.0s: subject",
Expand Down
4 changes: 2 additions & 2 deletions test/plugin/test_parser_json.rb
Original file line number Diff line number Diff line change
Expand Up @@ -10,7 +10,7 @@ def setup

sub_test_case "configure_json_parser" do
data("oj", [:oj, [Oj.method(:load), Oj::ParseError]])
data("json", [:json, [JSON.method(:load), JSON::ParserError]])
data("json", [:json, [JSON.method(:parse), JSON::ParserError]])
data("yajl", [:yajl, [Yajl.method(:load), Yajl::ParseError]])
def test_return_each_loader((input, expected_return))
result = @parser.instance.configure_json_parser(input)
Expand All @@ -28,7 +28,7 @@ def test_fall_back_oj_to_yajl_if_oj_not_available

result = @parser.instance.configure_json_parser(:oj)

assert_equal [JSON.method(:load), JSON::ParserError], result
assert_equal [JSON.method(:parse), JSON::ParserError], result
logs = @parser.logs.collect do |log|
log.gsub(/\A\d{4}-\d{2}-\d{2} \d{2}:\d{2}:\d{2} [-+]\d{4} /, "")
end
Expand Down

0 comments on commit 4f91c7f

Please sign in to comment.