Q:

how do I build a hash when using serialization?

how do I build a hash when using serialization?
{
  amount => [{year => total_cost}],
  amount => [{year => total_cost}],
  amount => [{year => total_cost}]
}

A:

Try this code. It mixes .map and .each_with_object to obtain the hash and array mix you describe:
namespace :data do
  task scrap: :environment do
    agent = Mechanize.new
    results = (3000..25000).step(1000).each_with_object({}) do |amount, h|

      year_costs = (1..5).step(1).map do |year|
          total_cost = agent.get("https://www.cashbuddy.se/api/loancost?amount=#{amount}&numberOfYears=#{year}").body
          {year => total_cost}
        end # => an array of hashes, as in your question.

      h[amount] = year_costs
    end

    Credit.create(credit_data: results)
  end
end

