Reputation: 21
I am trying to extract elements from this API response, but I am not able to for some reason. I have the following API response body: `
[
{
"ID": "295699",
"restriction": [
{
"restrictionTypeCode": "10001"
}
]
}
]
` Now, I simply want to print restrictionTypeCode
json_string = RestClient.get "#{$uri}", {:content_type => 'application/json'}
hash = JSON.parse(json_string)
code= hash['restriction']['restrictionTypeCode']
puts code
the above code errors out and it doesn't display the restrictionTypeCode
Upvotes: 2
Views: 83
Reputation: 12203
Your problem is your data is returning arrays in places. Try the following:
data = [
{
"ID": "295699",
"restriction": [
{
"restrictionTypeCode": "10001"
}
]
}
]
data.first[:restriction].first[:restrictionTypeCode]
# to make this safe from any nil values you may encounter, you might want to use
data.first&.dig(:restriction)&.first&.dig(:restrictionTypeCode)
# => "10001"
# or
data.flat_map { |hsh| hsh[:restriction]&.map { |sub_hsh| sub_hsh[:restrictionTypeCode] } }
# => ["10001"]
To break it down a little, your top level response and that falling under the key :restriction
both return arrays; therefore, to get the data from them you either need to access one of the items they contain (in my example using first
) or map them (the second example).
I've added some checks for nil
values in there: this is pretty vital when dealing with API responses as you're not in control of the data so can't be certain all the fields will be present. Rather than throw an error should you encounter data like this, you'll get nil
returned to avoid breaking subsequent code.
Hope this helps - let me know how you get on or if you have any questions :)
Upvotes: 3