I ran into the same issue. Dataset
and nested Association
s have a structure ideally suited for JSON export, but the JSON exporter only supports lists of rules. Any other type of expression triggers the error you see.
Export
The workaround is to recursively convert all nested associations to lists of rules.
normalAsc[expr_] := expr //. a_Association :> Normal[a]
normalAsc@Normal[dataset]
(* ==> {{"a" -> 1, "b" -> 2}, {"a" -> 3, "b" -> 4}} *)
This can now be exported to JSON.
ExportString[normalAsc@Normal[dataset], "JSON"]
(* "[
{
\"a\": 1,
\"b\": 2
},
{
\"a\": 3,
\"b\": 4
}
]" *)
Import
After importing JSON, we also need a way to convert it back to a nested association, then a Dataset
. This can be done as follows:
Dataset@Replace[json, {r__Rule} :> Association[r], {0, Infinity}]
The key here is to use Replace
, which scans the expression from the inside to outside. ReplaceAll
would go from the outside to the inside, and once a list of rules has been changed to an Association
, it won't be possible to replace inside it any more.
Update: Looks like there's a simpler way, ToAssociation
(undocumented).
A while ago I sent a suggestion to WRI support about allowing nested associations and possibly Dataset
to be exported to JSON. The more people suggest a feature, the more likely that it'll get implemented. You can consider suggesting it too.
Export
, which is probably a mess of special cases internally, doesn't seem to have been given the full update treatment in V10.0.0. It dosesn't handle the new structured data objects gracefully. We are probably stuck with this for now. Hopefully, it will be fixed in V10.0.1, coming real soon now (this month, according to WRI tech support). $\endgroup$ExportString
? $\endgroup$