Module: Rich::JSON

Defined in:
lib/rich/json.rb

Overview

JSON syntax highlighting and formatting

Constant Summary collapse

DEFAULT_STYLES =

Default styles for JSON elements

{
  key: "cyan",
  string: "green",
  number: "yellow",
  boolean: "italic magenta",
  null: "dim",
  brace: "bold",
  bracket: "bold",
  comma: "dim",
  colon: "dim"
}.freeze

Class Method Summary collapse

Class Method Details

.highlight(json_str, styles: {}) ⇒ Array<Segment>

Parse and render a JSON string

Parameters:

  • json_str (String)

    JSON string

  • styles (Hash) (defaults to: {})

    Style overrides

Returns:



52
53
54
55
56
57
# File 'lib/rich/json.rb', line 52

def highlight(json_str, styles: {})
  merged_styles = DEFAULT_STYLES.merge(styles)
  segments = []
  tokenize(json_str, merged_styles, segments)
  segments
end

.render(data, indent: 2, styles: {}) ⇒ Array<Segment>

Render JSON with syntax highlighting

Parameters:

  • data (Object)

    Data to render as JSON

  • indent (Integer) (defaults to: 2)

    Indentation size

  • styles (Hash) (defaults to: {})

    Style overrides

Returns:



29
30
31
32
33
34
35
36
# File 'lib/rich/json.rb', line 29

def render(data, indent: 2, styles: {})
  merged_styles = DEFAULT_STYLES.merge(styles)
  json_str = ::JSON.pretty_generate(data, indent: " " * indent)

  segments = []
  tokenize(json_str, merged_styles, segments)
  segments
end

.to_s(data, indent: 2, color_system: ColorSystem::TRUECOLOR) ⇒ String

Render to string with ANSI codes

Parameters:

  • data (Object)

    Data to render

  • indent (Integer) (defaults to: 2)

    Indentation

  • color_system (Symbol) (defaults to: ColorSystem::TRUECOLOR)

    Color system

Returns:

  • (String)


43
44
45
46
# File 'lib/rich/json.rb', line 43

def to_s(data, indent: 2, color_system: ColorSystem::TRUECOLOR)
  segments = render(data, indent: indent)
  Segment.render(segments, color_system: color_system)
end