Skip to content

Instantly share code, notes, and snippets.

@rohitn
Forked from szhorvat/formatJSON.m
Created October 25, 2021 01:19
Show Gist options
  • Save rohitn/18a2e215254813052cf04522d83acfa4 to your computer and use it in GitHub Desktop.
Save rohitn/18a2e215254813052cf04522d83acfa4 to your computer and use it in GitHub Desktop.
Format imported JSON for readability in Mathematica
formatJSON[json_] := formatRawJSON@rulesToAssociations[json]
rulesToAssociations[rules_] :=
Replace[rules, r : {__Rule} :> Association[r], {0, Infinity}]
basicTypeQ[_String | True | False | Null | (_?NumericQ)] = True;
basicTypeQ[_] = False;
formatRawJSON[json_] :=
Switch[json,
_?(AssociationQ[#] && VectorQ[Values[#], basicTypeQ] &),
Column@Normal[json],
_?AssociationQ,
Column@KeyValueMap[OpenerView[{#1, formatJSON[#2]}] &, json],
_?(ArrayQ[#, _, basicTypeQ] &),
TableForm[json],
_List,
Column[formatJSON /@ json, Frame -> All],
_,
json
]
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment