Module: JsonMend

Defined in:
lib/json_mend.rb,
lib/json_mend/parser.rb,
lib/json_mend/version.rb,
sig/json_mend.rbs

Overview

Root module

Defined Under Namespace

Classes: Parser

Constant Summary collapse

VERSION =

Returns:

  • (String)
'0.3.6'

Class Method Summary collapse

Class Method Details

.repair(json_string, return_objects: false) ⇒ Object, String

Repairs a broken JSON string.

Parameters:

  • json_string (String)

    The potentially broken JSON string.

  • return_objects (Boolean) (defaults to: false)

    If true, returns a Ruby object (Hash or Array), otherwise returns a valid JSON string.

  • (String)
  • return_objects: (Boolean) (defaults to: false)

Returns:

  • (Object, String)

    The repaired JSON object or string.



16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
# File 'lib/json_mend.rb', line 16

def repair(json_string, return_objects: false)
  # First, attempt to parse the string with the standard library.
  begin
    parsed = JSON.parse(
      json_string,
      allow_trailing_comma: true,
      allow_control_characters: true
    )

    # If the user wants objects, return them immediately
    return parsed if return_objects

    # Otherwise, generate the string once. This acts as both the
    # UTF-8 verification step AND the final string output.
    return JSON.generate(parsed)
  rescue JSON::ParserError, JSON::GeneratorError
    parser = Parser.new(json_string)
    repaired_json = parser.parse
  end

  # Avoids returning `null` for empty results, returns the object directly
  return repaired_json if return_objects

  # Always return a valid JSON string. For unparseable input, `nil` dumps to "null".
  JSON.dump(repaired_json)
end