1

The full example is here:

{-# LANGUAGE OverloadedStrings #-}
module Test2 where

import Data.Aeson
import Text.Mustache

main :: IO ()
main = do
  let example = Data.Aeson.object [ "key" .= (5 :: Integer), "somethingElse" .= (2 :: Integer) ]
  print . encode $ example
  print ("Start" :: String)
  case compileTemplate "" "{{{jsonData}}}" of
    Right x -> do
      print $ substituteValue x (Text.Mustache.object ["jsonData" ~= example])
    Left e -> error . show $ e

The above produces the following output:

"{\"somethingElse\":2,\"key\":5}"
"Start"
"fromList [(\"somethingElse\",2.0),(\"key\",5.0)]"

My expectation is it would produce:

"{\"somethingElse\":2,\"key\":5}"
"Start"
"{\"somethingElse\":2,\"key\":5}"
Chris Stryczynski
  • 30,145
  • 48
  • 175
  • 286

1 Answers1

1

Mustache doesn't seem to support straight substitution of JSON objects. Setting up a similar example here, I receive

[object Object]

as output. Not identical to yours, but it indicates that the issue is not necessarily with the Haskell implementation.

In other words, I believe the issue is with your template {{{jsonData}}}.

If you change it to {{{jsonData.somethingElse}}}, it works fine (I know this is not what you want).

Alternatively, encode the JSON data as text prior to passing it to the substitution function as suggested here. Basically something like this:

substituteValue x (Text.Mustache.object ["jsonData" ~= (encodeToLazyText jsonData)])

This results in your desired output. encodeToLazyText is found in Data.Aeson.Text.

Working code:

{-# LANGUAGE OverloadedStrings #-}

module Main where

import           Data.Aeson ((.=))
import qualified Data.Aeson as A
import           Data.Aeson.Text (encodeToLazyText)
import           Text.Mustache ((~=))
import qualified Text.Mustache as M
import qualified Text.Mustache.Types as M

main :: IO ()
main = do
  print . A.encode $ jsonData
  putStrLn "Start"
  case M.compileTemplate "" "in mustache: {{{jsonData}}}" of
    Right template ->
      print (M.substituteValue template mustacheVals)
    Left e -> 
      error . show $ e

jsonData :: A.Value
jsonData = 
  A.object
    [ "key" .= (5 :: Integer)
    , "somethingElse" .= (2 :: Integer)
    ]

mustacheVals :: M.Value
mustacheVals =
  M.object
    [ "jsonData" ~= encodeToLazyText jsonData
    ]
Community
  • 1
  • 1
Erik
  • 957
  • 5
  • 13