5
$\begingroup$

It seems that generally, Mathematica users (or at least the Q&A I've read here) prefer associations to represent data in ways that many other languages would use structures.

However, when Importing JSON files, Mathematica generates a list of rules.

Is there any clear advantage one way or the other? Is it just syntactical? Is there a reason Mathematica uses lists of rules for JSON instead of associations?

$\endgroup$
3
  • 2
    $\begingroup$ You can also import as an Association using the "RawJSON" format. $\endgroup$
    – Carl Woll
    Commented May 25, 2021 at 21:53
  • 3
    $\begingroup$ They're slightly different: for one, lists of rules can have multiple rules of the form key0 -> value for the same key0, e.g. {a -> x, b -> y, b -> z}. But if you convert this into an association, only the last key-value pair for a given key will be kept: Association[{a -> x, b -> y, b -> z}] gives <|a -> x, b -> z|>. I don't know, but I imagine this might be one reason to maintain a difference. $\endgroup$
    – thorimur
    Commented May 25, 2021 at 22:16
  • 1
    $\begingroup$ Association is newer and has several advantages, which are discussed elsewhere on this site. Since it’s newer, old functionality that returned lists may still do so, for the sake of compatibility. They work differently, since pattern -> replacement has a different intention than key -> value. Thus Reverse /@ {x -> a, y -> b} inverts the mapping represented by the list; mapping any function (like Reverse) on an association applies the function to each value. Etc. The different semantics make each useful for different applications. Association is intended to represent key/value data. $\endgroup$
    – Michael E2
    Commented May 25, 2021 at 23:04

0

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Browse other questions tagged or ask your own question.