【发布时间】:2017-08-02 09:26:24
【问题描述】:
我收到了一个 JSON 对象形式的 FullContact API 响应,其中包含一些包含一组联系人详细信息的嵌套数组。我想在我的 Rails 应用程序控制器中创建一个对象,该对象包含响应中的任何信息。我正在尝试使用如下代码执行此操作(请注意,我使用的 gem 允许使用点符号访问对象):
@automatic_profile = AutomaticProfile.new(
profile_id: @profile.id,
first_name: @intel.contact_info.full_name,
email: @profile.email,
gender: @intel.demographics.gender,
city: @intel.demographics.location_deduced.city.name,
skype: @intel.contact_info.chats.select { |slot| slot.client == "skype" }[0].handle),
organization_1: @intel.organizations[0].name if @intel.organizations,
# other similar lines for other organizations
twitter: (@intel.social_profiles.select { |slot| slot.type_name == "Twitter" }[0].url if @intel.social_profiles),
twitter_followers: (@intel.social_profiles.select { |slot| slot.type_name == "Twitter" }[0].followers.to_i) if @intel.social_profiles,
twitter_following: (@intel.social_profiles.select { |slot| slot.type_name == "Twitter" }[0].following.to_i if @intel.social_profiles),
# other similar lines for other social profiles
)
这段代码有两个问题:
- Json 对象并不总是具有填充某些哈希键所需的所有信息,因此例如在调用不存在的数组中的索引时会引发异常。
我尝试在每一行中添加一个 if 语句,如下所示:
twitter: (@intel.social_profiles.select { |slot| slot.type_name == "Twitter" }[0].url if @intel.social_profiles),
但它不是 DRY,我对括号的使用感到很困惑,以至于我提出了额外的例外。
- 为了给我的键设置正确的值,我使用 slot 方法来查找我正在寻找的特定数据。这似乎也很冗长,不太实用。
您能否就使用嵌套数组响应的大 Json 数据创建对象的最佳实践提出建议,并就如何解决这种特殊情况提出建议?
【问题讨论】:
标签: ruby-on-rails arrays json ruby