This is part of the Semicolon&Sons Code Diary - consisting of lessons learned on the job. You're in the data category.
Last Updated: 2024-11-21
A script of mine whose job was to match (SQL) database objects with JSON data failed, in the sense of returning all nils in the mapped output.
Here is the code:
tutor_data = JSON.read("tutors.json")
Tutor.where(state: "accepted").map do |tutor|
# The problematic line...
tutor_data.find {|e| e[:id] == tutor.id}
end
The issue was that technically speaking the :id
fields in the (rubyified) JSON
was nil - all that was available was the "id"
field - i.e. a string field, not
a symbol field (which are standard with Ruby's hashes, themselves deceptively JSON-like
structures).
It is better, therefore, to keep it simple and always use strings keys when working with JSON.
tutor_data.find {|e| e["id"] == tutor.id}