1

Possible Duplicate:
Parsing a JSON string in ruby

I've managed to get a bunch of json into a variable in ruby and print it out, through the JSON gem and the following code:

require 'open-uri'
require 'json'

result = JSON.parse(open("https://api.pinboard.in/v1/posts/get?auth_token=username:token&tag=fashion&meta=yes&format=json").read)
puts result

What it returns is this:

{
  "date"=>"2012-09-24T03:35:38Z",
  "user"=>"username",
  "posts"=>[{
      "href"=>"http://example.com/example.jpg",
      "description"=>"this is the description",
      "extended"=>"A full, longer description.",
      "meta"=>"d6f967c9adfbe1eb3763fddbcd993d1b",
      "hash"=>"a46e0e7202d9d56c516a472d8be70d9e",
      "time"=>"2012-09-24T03:35:38Z",
      "shared"=>"yes",
      "toread"=>"no",
      "tags"=>"fashion"
    }
]}

(the line-spacing here is mine, for clarity)

My problem is, I have no idea how to access these keys and values! I've googled and searched but I'm really new to ruby and I'm having a lot of trouble figuring out exactly what I'm supposed to be doing, nevermind the code to do it. Help?

Community
  • 1
  • 1
zakkain
  • 95
  • 2
  • 6

2 Answers2

2

result["date"] - accesses the date key on the json.

In general result[<key>] accesses the value stored in key.

If you try to access a key that does not exists you will get nil as a result.

Edit: In order to traverse the key/value pairs you can:

result.each do |key, value|
   puts "result[#{key}] = #{value}"
end
Erez Rabih
  • 15,562
  • 3
  • 47
  • 64
  • Oh wow, that's embarrassing for me. Thanks! How would I grab the name of the key itself, say if I wanted to loop through all the keys and values and print each key name next to its value? – zakkain Sep 24 '12 at 15:05
  • You'd use `Hash.keys`, but before that you'd read through [Ruby's documentation](http://www.ruby-doc.org/docs/ProgrammingRuby/html/tut_classes.html) about accessing [arrays](http://www.ruby-doc.org/core-1.9.3/Array.html) and [hashes](http://www.ruby-doc.org/core-1.9.3/Hash.html) which covers all this. – the Tin Man Sep 24 '12 at 15:40
0

Do stuff like:

p result["date"]
p result["posts"].size

Look up the documentation for the ruby Array and Hash classes.

David Grayson
  • 84,103
  • 24
  • 152
  • 189