Skip to content

Instantly share code, notes, and snippets.

@vderyagin
Last active December 10, 2015 14:19
Show Gist options
  • Select an option

  • Save vderyagin/4446915 to your computer and use it in GitHub Desktop.

Select an option

Save vderyagin/4446915 to your computer and use it in GitHub Desktop.
querying json data
require 'json'
data1 = JSON.load('{"status": "fail", "messages": ["Out of capacity"]}')
data2 = JSON.load('{"status": "success", "messages": [], "result": {"node": {"ip": "1.2.3.4", "description": "", "id": 974, "name": "VM#3"}}}')
def get_from_json(data, query)
query.split('.').inject(data) do |memo, key|
key = key.to_i if memo.is_a?(Array)
memo.fetch(key)
end
end
get_from_json(data1, 'messages.0') # => "Out of capacity"
get_from_json(data2, 'result.node.ip') # => "1.2.3.4"
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment