1

I get the following JSON response for Alpha vantage Stock API:

    "Time Series (Daily)": {
        "2018-07-09": {
            "1. open": "142.6000",
             ...
        },

I get different dates depending on the location of the stock exchange. On some, it might say "2018-07-09", and on others "2018-07-10".

Is there a way to reach the attributes of an object without typing the object, something along the lines of:

["Time Series (Daily)"]["first_child"]["1. open"]

Using:

["Time Series (Daily)"][0]["1. open"]

doesn't work.

sawa
  • 165,429
  • 45
  • 277
  • 381
Crashtor
  • 1,249
  • 1
  • 13
  • 21
  • This seems relevant. https://stackoverflow.com/questions/983267/ Worth mentioning that this will be somewhat performance-taxing if your object is very large/has many properties. – getfugu Jul 10 '18 at 02:27
  • Thanks for that, I've looked at that question, however it doesn't help me that much as I'm parsing it with rails. Using the index of [0], returns nothing. – Crashtor Jul 10 '18 at 02:31

2 Answers2

4
ruby_hash["Time Series (Daily)"].values.first["1. open"]
sawa
  • 165,429
  • 45
  • 277
  • 381
1

Adapted from How can I get the key Values in a JSON array in ruby?

require 'json'
myData = JSON.parse('{"A": {"B": {"C": {"D": "open sesame"}}}}')

def getProperty(index, parsedData)
  return parsedData[parsedData.keys[index]]
end  

myDataFirstProperty = getProperty(0, myData) # => {"B"=>{"C"=>{"D"=>"open sesame"}}}

evenDeeper = getProperty(0, myDataFirstProperty) # => {"C"=>{"D"=>"open sesame"}}

This answer can also get the Nth property of the JSON, unlike the accepted answer which can only get the first.

getfugu
  • 140
  • 1
  • 5
  • This only gets me to where I would before, ( ["2018-07-09"] ) - I need to go 1 step down. I feel like such a noob. – Crashtor Jul 10 '18 at 02:58
  • Use `keys` again on the next object within json. https://repl.it/repls/SophisticatedFavorableRobodoc. Worth noting that my answer can get properties other than the first property, which cannot be done with the accepted answer. – getfugu Jul 10 '18 at 03:09