Rails 5中如何从嵌套JSON数组获取transactionCustomFields的token
在Rails 5中获取JSON里指定自定义字段的值
假设你已经拿到了JSON响应字符串,或是通过Webhook接收的参数,以下是具体实现步骤:
1. 解析JSON字符串(如果是原始JSON的话)
如果你的响应是原始JSON字符串,先将其转换为Ruby哈希:
# 替换为你的实际JSON响应字符串 json_response = '{ "event":"TRANSACTION OUTCOME", "timestamp":1672749136029, "data":{ "transactionId":"b5247b19-1e14-4f3e-818f-a3b1554dd64b", "transactionStatus":"SUCCESS", "statusDescription":"SUCCESS", "transaction":{ "id":"b5247b19-1e14-4f3e-818f-a3b1554dd64b", "paymentMethod":"MOBILE_MONEY", "transactionType":"PULL", "phoneNumber":"+256754187853", "telecom":"AIRTEL", "amount":500, "status":"SUCCESS", "narration":"", "failedDescription":null, "webhookUrl":"https://webhook.site/cbf423c2-15f5-46f3-9c76-1dcc0b9a2e18", "createdAt":"2023-01-03T12:32:04.176Z", "transactionCustomFields":[ {"id":"1fc25a5c-ba0b-4959-b295-31628d8da0e1","key":"token","value":"31644"}, {"id":"2686effb-4f40-45ac-867f-b39d84282dae","key":"reference","value":"1672749122"} ] } } }' # 解析为Ruby哈希 response_hash = JSON.parse(json_response)
2. 定位到自定义字段数组
用dig方法安全导航到transactionCustomFields数组,避免层级不存在时抛出错误:
custom_fields = response_hash.dig('data', 'transaction', 'transactionCustomFields')
如果是在Webhook控制器中处理参数(Rails会自动解析为参数哈希),可直接使用符号键:
custom_fields = params.dig(:data, :transaction, :transactionCustomFields)
3. 获取key为token的value值
用find方法筛选目标字段,再提取value。同时使用安全操作符&.避免字段不存在时报错:
# 针对字符串键的哈希 token_value = custom_fields.find { |field| field['key'] == 'token' }&.[]('value') # 针对符号键的参数哈希 token_value = custom_fields.find { |field| field[:key] == 'token' }&.[]('value')
执行后,token_value的值为"31644";若找不到key为token的字段,token_value会返回nil。
内容的提问来源于stack exchange,提问作者Asher Namanya
相关产品推荐
相关产品推荐

