JuliaLang / IJulia.jl

Julia kernel for Jupyter
MIT License
2.78k stars 409 forks source link

Displaying JSON data #934

Open jlumpe opened 4 years ago

jlumpe commented 4 years ago

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.

stevengj commented 4 years ago

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

jlumpe commented 4 years ago

There seems to be two separate display systems in place:

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.