From 9c0005ef67bfae7d647e8d54e4fb668b807c2963 Mon Sep 17 00:00:00 2001 From: Daijiro Fukuda Date: Tue, 21 Mar 2023 11:12:21 +0900 Subject: [PATCH] Make sure JSON parser returns Hash Record must be Hash. Signed-off-by: Daijiro Fukuda --- lib/fluent/plugin/parser_json.rb | 3 +++ test/plugin/test_parser_json.rb | 26 ++++++++++++++++++++++++++ 2 files changed, 29 insertions(+) diff --git a/lib/fluent/plugin/parser_json.rb b/lib/fluent/plugin/parser_json.rb index 840f6a963c..641663e596 100644 --- a/lib/fluent/plugin/parser_json.rb +++ b/lib/fluent/plugin/parser_json.rb @@ -71,6 +71,9 @@ def configure_json_parser(name) def parse(text) record = @load_proc.call(text) + # Sometimes the parser returns String, not Hash. + # Ex. Oj.load('"hoge"') => "hoge" + raise @error_class unless record.is_a?(Hash) time = parse_time(record) if @execute_convert_values time, record = convert_values(time, record) diff --git a/test/plugin/test_parser_json.rb b/test/plugin/test_parser_json.rb index 19c45402d1..fb8947581f 100644 --- a/test/plugin/test_parser_json.rb +++ b/test/plugin/test_parser_json.rb @@ -135,4 +135,30 @@ def test_yajl_parse_io_with_buffer_smaller_than_input end end end + + sub_test_case "various record pattern" do + data("Only string", { record: '"message"', exepected: nil }, keep: true) + data("Only string without quaot", { record: "message", exepected: nil }, keep: true) + data("Only number", { record: "0", exepected: nil }, keep: true) + def test_oj(data) + @parser.configure('json_parser' => "oj") + @parser.instance.parse(data[:record]) { |time, record| + assert_equal(data[:expected], record) + } + end + + def test_yajl(data) + @parser.configure('json_parser' => "yajl") + @parser.instance.parse(data[:record]) { |time, record| + assert_equal(data[:expected], record) + } + end + + def test_json(json) + @parser.configure('json_parser' => "json") + @parser.instance.parse(data[:record]) { |time, record| + assert_equal(data[:expected], record) + } + end + end end