What is the best way to convert an expression to a string in a reversible manner?
I need a toStr
function so that it is always true that
ToExpression@toStr[expr] === expr
ToString
is not satisfactory because it may use special, irreversible formatting. Example:
ToString[Graphics[{Circle[{0,0}]}]]
(* "-Graphics-" *)
In this case the problem is that it uses OutputForm
by default. Requesting InputForm
would solve this. But then consider
Format[x, InputForm] = "foo"
ToString[x, InputForm]
(* "foo" *)
x
does exist as a proper expression in-memory. It can be written to disk by exporting to MX and then reliably re-imported. I am looking for the same functionality, but through strings.
Note: I am aware that there are some expressions which can't be safely cycled through a string, or even through Compress
or through MathLink. An example would be
asc = <| a -> 1|>
a = 5;
asc
(* <| a -> 1|> *)
ToExpression@ToString[asc] (* or use Uncompress@Compress[...] if you like *)
(* <| 5 -> 1 |> *)
I am not aiming to solve these types of difficulties, which are separate from my main problem.
InputForm
does not actually solve this completely, as it returns"Graphics[{Circle[{0, 0}]}]"
$\endgroup$Circle[]
evaluating toCircle[{0,0}]
. I changed the example to readCircle[{0,0}]
to avoid misunderstanding. I do not need to prevent evaluation, just to cycle an expression through a string reliably. $\endgroup$ToString[HoldForm[a]]
if necessary? $\endgroup$"ExpressionJSON"
help? For example,str=ExportString[Graphics[{Circle[{0, 0}]}], "ExpressionJSON", "Compact" -> True]
thenImportString[#,"ExpressionJSON"]&@str
. $\endgroup$