Sha256: 22b03fd8d2e6ef6338540425fe9b3ea7632edb1e8f775c052df0ef0cb345afe4

Contents?: true

Size: 1.6 KB

Versions: 27

Compression:

Stored size: 1.6 KB

Contents

# frozen_string_literal: true

module Karafka
  # Module for all supported by default parsers for incoming/outgoing data
  module Parsers
    # Default Karafka Json parser for serializing and deserializing data
    class Json
      # @param content [String] content based on which we want to get our hash
      # @return [Hash] hash with parsed JSON data
      # @example
      #   Json.parse("{\"a\":1}") #=> { 'a' => 1 }
      def self.parse(content)
        ::MultiJson.load(content)
      rescue ::MultiJson::ParseError => e
        raise ::Karafka::Errors::ParserError, e
      end

      # @param content [Object] any object that we want to convert to a json string
      # @return [String] Valid JSON string containing serialized data
      # @raise [Karafka::Errors::ParserError] raised when we don't have a way to parse
      #   given content to a json string format
      # @note When string is passed to this method, we assume that it is already a json
      #   string and we don't serialize it again. This allows us to serialize data before
      #   it is being forwarded to a parser if we want to have a custom (not that simple)
      #   json serialization
      #
      # @example From an ActiveRecord object
      #   Json.generate(Repository.first) #=> "{\"repository\":{\"id\":\"04b504e0\"}}"
      # @example From a string (no changes)
      #   Json.generate("{\"a\":1}") #=> "{\"a\":1}"
      def self.generate(content)
        return content if content.is_a?(String)
        return content.to_json if content.respond_to?(:to_json)
        raise Karafka::Errors::ParserError, content
      end
    end
  end
end

Version data entries

27 entries across 27 versions & 1 rubygems

Version Path
karafka-1.2.13 lib/karafka/parsers/json.rb
karafka-1.2.12 lib/karafka/parsers/json.rb
karafka-1.2.11 lib/karafka/parsers/json.rb
karafka-1.2.10 lib/karafka/parsers/json.rb
karafka-1.2.9 lib/karafka/parsers/json.rb
karafka-1.2.8 lib/karafka/parsers/json.rb
karafka-1.2.7 lib/karafka/parsers/json.rb
karafka-1.2.6 lib/karafka/parsers/json.rb
karafka-1.2.5 lib/karafka/parsers/json.rb
karafka-1.2.4 lib/karafka/parsers/json.rb
karafka-1.2.3 lib/karafka/parsers/json.rb
karafka-1.2.2 lib/karafka/parsers/json.rb
karafka-1.2.1 lib/karafka/parsers/json.rb
karafka-1.2.0 lib/karafka/parsers/json.rb
karafka-1.2.0.beta4 lib/karafka/parsers/json.rb
karafka-1.2.0.beta3 lib/karafka/parsers/json.rb
karafka-1.2.0.beta2 lib/karafka/parsers/json.rb
karafka-1.2.0.beta1 lib/karafka/parsers/json.rb
karafka-1.1.2 lib/karafka/parsers/json.rb
karafka-1.1.1 lib/karafka/parsers/json.rb