Skip to content

Instantly share code, notes, and snippets.

@imtiaz-emu
Last active February 16, 2021 05:15
Show Gist options
  • Save imtiaz-emu/1e96be0999d4edf0bb40d8b9db2ff4f2 to your computer and use it in GitHub Desktop.
Save imtiaz-emu/1e96be0999d4edf0bb40d8b9db2ff4f2 to your computer and use it in GitHub Desktop.
Extract Data from a JSON (Ruby)
require 'active_support/core_ext/hash'
# Input: 'extra:[1:main:[5:provider]]'
# Output: ['extra', 1, 'main', 5, 'provider']
def macro_key_parser(str, keys = [])
first_key = str
first_key, second_key = str.split(':', 2) if first_key[0] != '['
if first_key[0] != '['
keys << first_key.strip
macro_key_parser(second_key, keys)
else
arr_index, first_key = first_key[1...(first_key.length-1)].split(':', 2)
keys << arr_index.strip.to_i
macro_key_parser(first_key, keys)
end
return keys
rescue
str.split(':')
end
# ================== Example ================== #
example = {
"data": {
"match_id": 137046,
"league_id": 237,
"match_statistics": [
{
"team_id": 2509,
"team_name": "Liverpool FC"
},
{
"team_id": 2589,
"team_name": "Leeds United FC"
}
]
}
}
# To get the team_name 'Leeds United FC'
digger = macro_key_parser("data:match_statistics:[1:team_name]", keys = [])
example.with_indifferent_access.dig(*digger)
# To get the team_name 'Liverpool FC'
digger = macro_key_parser("data:match_statistics:[0:team_name]", keys = [])
example.with_indifferent_access.dig(*digger)
# Explanation of the method `macro_key_parser(str, keys = [])`
# A Json data may contain hashes and inside hashes may contain arrays. or vice versa.
# if we have hash inside hash, to access the inner hash, we'll use "outer_hash_key:inner_hash_key"
# From the example json above, `data:match_statistics` will return an array by the method.
# if any hash contains array, that means the array has 1 or 1+ elements. To access the array element, we'll use "hash_key:[array_element_index]"
# From the example json above, `data:match_statistics:[0]` will return a hash.
# if any array contains hash, we'll use "[array_element_index:hash_key]"
# From the example json above, `data:match_statistics:[0:team_name]` will return a string.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment