2

I am thinking of writing a web application that crawls an API and returns this information in JSON form.

However, I am only after one number, then current price (in this sample, "227"). How can I access that in Ruby? I have no clue where to begin. I've never dealt with text like this.

For discussion's sake, suppose I save this output into instance variable @information

{
    "item": {
        "icon": "http://services.runescape.com/m=itemdb_rs/4332_obj_sprite.gif?id=4798",
        "icon_large": "http://services.runescape.com/m=itemdb_rs/4332_obj_big.gif?id=4798",
        "id": 4798,
        "type": "Ammo",
        "typeIcon": "http://www.runescape.com/img/categories/Ammo",
        "name": "Adamant brutal",
        "description": "Blunt adamantite arrow...ouch",
        "current": {
            "trend": "neutral",
            "price": 227
        },
        "today": {
            "trend": "neutral",
            "price": 0
        },
        "day30": {
            "trend": "positive",
            "change": "+1.0%"
        },
        "day90": {
            "trend": "positive",
            "change": "+1.0%"
        },
        "day180": {
            "trend": "positive",
            "change": "+2.0%"
        },
        "members": "true"
    }
}
Wayne Conrad
  • 103,207
  • 26
  • 155
  • 191
Dylan Richards
  • 708
  • 1
  • 13
  • 33

2 Answers2

2

First follow this post to parse this JSON in to Hash Parsing a JSON string in Ruby

say the parsed hash name is my_hash then the following should give you price

my_hash['item']['current']['price']

Edit:

As you said you want to save it in @information

@information = my_hash['item']['current']['price']
Community
  • 1
  • 1
Hardik
  • 3,815
  • 3
  • 35
  • 45
0

Even you can use hashie it gives your json into readable structural code

Install Hashie

gem install hashie

then in your code all that json take in a variable my_json

myhash = Hashie::Mash.new(my_json)

@information = my_hash.item.current.price

Tips:- if your json is dynamic and it may respond some other structural element so you can maintain exceptional code

@information = my_hash.item.try(:current).try(:price)

Kishore Mohan
  • 1,020
  • 1
  • 9
  • 15