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?

2
  • 1
    This has nothing to do with json. It is about accessing values within a hash. Commented Sep 24, 2012 at 15:29
  • Possible duplicates: stackoverflow.com/q/9055096/128421. Commented Sep 24, 2012 at 15:38

2 Answers 2

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
Sign up to request clarification or add additional context in comments.

2 Comments

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?
You'd use Hash.keys, but before that you'd read through Ruby's documentation about accessing arrays and hashes which covers all this.
0

Do stuff like:

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

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

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.