Module: Contrast::Utils::Json

Extended by:
Components::Logger::InstanceMethods
Defined in:
lib/contrast/utils/json.rb

Overview

Module to hold Agent’s custom JSON.parse logic.

Constant Summary collapse

SPECIAL_CASES =

Add any known cases where parsing error might arise from older json parser:

Returns:

[nil, "", "\"\"", "\"0\""].cs__freeze

Class Method Summary collapse

Methods included from Components::Logger::InstanceMethods

cef_logger, logger

Class Method Details

.parse(string, deep_symbolize: false) ⇒ Hash

Parses a string using JSON.parser. This method is used instead of standard JSON.parse to support older versions of json gem => not supporting key-value second parameter, which is supported after json 2.3.0.

Parameters:

  • string (String)
  • deep_symbolize (Boolean) (defaults to: false)

    flag to set if keys needs to be deep symbolized.

Returns:



26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
# File 'lib/contrast/utils/json.rb', line 26

def parse string, deep_symbolize: false
  # The Agent receives empty responses from TS sometimes.
  # There is a special case to handle this.
  return {} if SPECIAL_CASES.include?(string)

  symbolized_hash = {}
  hash = JSON::Parser.new(string).parse
  symbolized_hash = Contrast::Utils::HashUtils.deep_symbolize_all_keys(hash) if deep_symbolize
  return hash unless deep_symbolize

  symbolized_hash
rescue JSON::ParserError => e
  # Any parsing error will produce empty {}. Since older JSON might pose support issues with newer Ruby,
  # We might just log any miss-parsings and allow Agent to continue.
  logger.warn("[JSON] parse error: #{ e }")
  {}
end