I would like to be able to examine a runtime javascript object. Can I print an object to the console instead of a string?
You can use Debug.log, for example:
import Html exposing (text)
f x = x * x
main =
let
dummy = Debug.log "dump tuple" (33, 55, f)
in text "Hello, World!"
Unfortunately, no. All objects are converted to strings before they are sent to the console when you use Debug.log.
You can however create a function that would output the actual object using the Native layer however, this is an undocumented API and it is advisable to use it only as a last resort.
I needed richer logging while working on an encoder, so I ended up writing a port for it. Here's an working example on Ellie and here's the code:
port module Main exposing (main)
import Browser
import Html exposing (Html, button, div, text)
import Html.Events exposing (onClick)
import Json.Encode as E exposing (Value, int, object, string)
type alias Model =
{ count : Int
, name : String
}
initialModel : Model
initialModel =
{ count = 0
, name = "Foo"
}
encodeModel : Model -> Value
encodeModel model =
object
[ ( "count", int model.count )
, ( "name", string model.name )
]
port jsonConsole : Value -> Cmd msg
type Msg
= ConsoleLogJson
update : Msg -> Model -> ( Model, Cmd Msg )
update msg model =
case msg of
ConsoleLogJson ->
let
json =
encodeModel model
in
( model, jsonConsole json )
view : Model -> Html Msg
view model =
div [] [ button [ onClick ConsoleLogJson ] [ text "Log to console" ] ]
subscriptions : Model -> Sub Msg
subscriptions _ =
Sub.batch []
init : () -> ( Model, Cmd msg )
init flags =
( initialModel, Cmd.none )
main : Program () Model Msg
main =
Browser.element
{ init = init
, subscriptions = subscriptions
, view = view
, update = update
}
<html>
<head>
<style>
/* you can style your program here */
</style>
</head>
<body>
<main></main>
<script>
var app = Elm.Main.init({ node: document.querySelector('main') })
app.ports.jsonConsole.subscribe(function(json) {
console.log(json)
})
</script>
</body>
</html>
I'm sure there are improvements that could be made, and I'd love to hear them!
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With