6
$\begingroup$

I have the following sample JSON file:

{"attr1": "Sample with val1"}

When I parse it as JSON I get the expected output:

Import["test.json", "JSON"]
{attr1 -> Sample with val1}

Now I create the following FileTemplate:

{"attr1": "Sample with `val1`"}

And I run:

tpl = FileTemplate["testTpl.txt"];
tplVal = <|"val1" -> "testVal1"|>;
res = TemplateApply[tpl, tplVal];
{res, Head@res} (* {{"attr1" -> "Sample with testVal1"}, String} *)

This is all as expected. I would like to save the results of the various TemplateApplys to disk (or a database table) and read back the saved items as JSON. However, the following does not appear to work:

Export["test1.json", TemplateApply[tpl, tplVal]]

The saved file escapes the quotation marks:

{\"attr1\": \"Sample with testVal1\"}

which throws an error in any subsequent attempt to parse it as JSON.

Is there an easy solution to this problem? The larger question might be whether this is the idiomatic way to store and reify JSON-based file templates in Wolfram Language. How should this problem be approached?

$\endgroup$
8
$\begingroup$

We can recreate this problem more easily with the following code:

Export["test.json", "{\"attr1\": \"Sample with `val1`\"}"]

What happens is that Export looks at the file extension .json and tries to turn the second argument into valid JSON, treating it as if it were a symbolic representation of JSON in Mathematica. Compare with this:

Export["~/Desktop/test.json", <|"attr1" -> "Sample with testVal1"|>]

which gives the result that you expect. This also gives what you expect:

Export["~/Desktop/test.txt", "{\"attr1\": \"Sample with `val1`\"}"]

because now the file ending is .txt so Export doesn't try to consider the second argument to be a symbolic Wolfram Language representation of JSON.

You can use the third argument of Export to tell it to not regard the second argument as JSON representation, but rather as text, even in the presence of the .json extension:

Export["~/Desktop/test.json", res, "Text"]

This will also work as you expect.

$\endgroup$
  • $\begingroup$ Perfect! Thank you very much. $\endgroup$ – Shredderroy Jan 9 '18 at 4:38

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.