The introduction of Assocation brings a powerful new way to handle this problem.
- Version 10.2 provides forprovides for import of JSON as nested associations without use of
ToAssociationsby using the format"RawJSON".
(* archive data *) ad = {"accept_rate" -> 75, "account_id" -> 395497, "age" -> 41, "badge_counts" -> {"bronze" -> 35, "gold" -> 0, "silver" -> 11}, "creation_date" -> 1326833982, "display_name" -> "Verbeia", "is_employee" -> False, "last_access_date" -> 1331949804, "last_modified_date" -> 1330990001, "link" -> "http"https://mathematica.stackexchange.com/users/8/verbeia", "location" -> "Sydney, Australia", "profile_image" -> "http://www.gravatar.com/avatar/3df2379fc0221bb0281c0d608542bd84?d=\ identicon&r=PG", "reputation" -> 3571, "reputation_change_day" -> 0, "reputation_change_month" -> 857, "reputation_change_quarter" -> 3475, "reputation_change_week" -> 605, "reputation_change_year" -> 3475, "user_id" -> 8, "user_type" -> "registered", "website_url" -> "http://www.verbeia.com/mathematica"}; Convert to nested Association (reference: Converting hierarchies of rules to associationsConverting hierarchies of rules to associations)
Needs["GeneralUtilities`"] asc = ToAssociations[ad]; Query a value:
asc["badge_counts", "silver"] 11
Missing values are automatically handled:
asc["badge_counts", "platinum"] Missing["KeyAbsent", "platinum"]
Perform multiple lookups at once:
lookups = {{"display_name"}, {"creation_date"}, {"reputation"}, \ {"reputation_change_week"}, {"is_employee"}, {"last_access_date"}, {"user_type"}, \ {"badge_counts", "bronze"}, {"badge_counts", "silver"}, {"badge_counts", "gold"}, {"badge_counts", "platinum"}}; Extract[asc, lookups] {"Verbeia", 1326833982, 3571, 605, False, 1331949804, "registered", 35, 11, 0, Missing["KeyAbsent", "platinum"]}
More advanced queries are easy. With current data:
data = Import[ "http://api.stackexchange.com/2.0/users?page=1&order=desc&sort=reputation&site=\ mathematica", "JSON"] // ToAssociations; Find my current bronze badge count:
data // Query["items", Select @ MemberQ @ "Mr.Wizard", "badge_counts", "bronze"] {632}