3

I have a large amount of nested data formatted in JSON.

I would like to select for a single element:

{"data": [ {"id": "123456","from": {"name": "Jason Wade","id": "654321"},"message": "http://www.youtube.com/watch?v=ZfXHAqBRIEk" ...

  1. How do I efficiently select for a single element, say "message"?

  2. Is there a simple recommended method for this? Say convert it to an array, or something?

  3. Could you point me to some reading for parsing JSON?

Thanks!

user398520
  • 1,553
  • 3
  • 12
  • 11
  • possible duplicate of [Rails and JSON: a beginner's question](http://stackoverflow.com/questions/1826727/rails-and-json-a-beginners-question) – rubyprince Feb 26 '11 at 05:47

1 Answers1

3

If you are using Rails, see the question in my comment. If you are using pure Ruby, there is a gem called json. Install the gem, and use like this

require 'rubygems'
require 'json'
url = "www.example.com/api?format=json"
response = Net::HTTP.get_response(URI.parse(url))
data = response.body
result = JSON.parse(data)

JSON format and ruby data types have similarity and in your example, the result will be a hash like this

{"data"=>[{"message"=>"http://www.youtube.com/watch?v=ZfXHAqBRIEk", "from"=>{"name"=>"Jason Wade", "id"=>"654321"}, "id"=>"123456"}]}
rubyprince
  • 17,559
  • 11
  • 64
  • 104