IJulia.jl icon indicating copy to clipboard operation
IJulia.jl copied to clipboard

Displaying JSON data

Open jlumpe opened this issue 4 years ago • 2 comments

Jupyter has a special type of output cell for JSON data, which you can get in Python by wrapping parsed data (dict or list) in a IPython.display.JSON object and displaying it using IPython's built-in display machinery (just having it as the last line of a cell is enough). Is there an equivalent way to do this in IJulia, using a value from JSON.parse?

The closest thing I can get is display(MIME"application/json"(), s::String) which triggers the correct output cell type, but only displays the literal string s. This method does not work for Dict or Array.

jlumpe avatar Jun 27 '20 18:06 jlumpe

Wouldn't it be sufficient to add application/json to this list?

stevengj avatar Aug 19 '20 13:08 stevengj

There seems to be two separate display systems in place:

  • display(::InlineDisplay, x) calls display_dict(x), which calls display_mimestring(mime, x) and display_mimejson(mime, x) for all MIME types in ijulia_mime_types and ijulia_jsonmime_types. Both of these ultimately call limitstringmime(mime, x).
  • display(::InlineDisplay, ::MIME, x) calls limitstringmime directly.

The following works for the first system:

const JSON_TYPES = [String, Real, Nothing, Bool, Array, Dict]

for T in JSON_TYPES
    @eval begin
        IJulia._showable(::MIME"application/json", ::$T) = true
        IJulia.display_mimejson(mime::MIME"application/json", x::$T) = (mime, JSON.JSONText(JSON.json(x)))
    end
end

IJulia.register_jsonmime(MIME"application/json"())

but then the JSON output format is always used for displaying these types, which isn't what's desired.

Ideally you should just be able to call display([::InlineDisplay], MIME"application/json"(), value), which uses the 2nd system. The default (not specialized by MIME type) method calls limitstringmime(mime, x) on the first line, which tests istextmime(mime) == true => israwtext(x) == false => show(InlineIOContext(buf), mime, x) which throws a MethodError. It's not clear how to specialize the behavior here for JSON - specialized display methods all also call limitstringmime and limitstringmime itself only has one method.

jlumpe avatar Aug 19 '20 21:08 jlumpe