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.

2
  • This seems relevant. stackoverflow.com/questions/983267 Worth mentioning that this will be somewhat performance-taxing if your object is very large/has many properties. Commented Jul 10, 2018 at 2: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. Commented Jul 10, 2018 at 2:31

2 Answers 2

4
ruby_hash["Time Series (Daily)"].values.first["1. open"]
Sign up to request clarification or add additional context in comments.

3 Comments

Syntax error? @result = @parse_result["Time Series (Daily)"]values.first["1. open"]
@Crashtor Sorry, missed a period before values. Fixed.
This answer solves this specific case, but it does not handle retrieving properties other than the first one of the object.
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.

2 Comments

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.
Use keys again on the next object within json. 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.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.