Module: JsonMend

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

Overview

Root module

Defined Under Namespace

Classes: Parser

Constant Summary collapse

VERSION =
'0.3.1'

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.

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
# File 'lib/json_mend.rb', line 16

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

    # Verify the native parser didn't produce invalid UTF-8 (like unpaired surrogates)
    # by ensuring it can safely dump its own output.
    JSON.generate(parsed)

    parsed
  rescue JSON::ParserError, JSON::GeneratorError
    parser = Parser.new(json_string)
    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