Home > Software engineering >  extracting nested values from JSON using Ruby
extracting nested values from JSON using Ruby

Time:03-17

I want to extract the individual values by key out of this JSON.

json = JSON.parse({ "streams": [ { "index": 0, "codec_name": "mpeg2video"} ] })

Using json['streams'].each do |codec_name| returns the whole first array back. I also tried identifying specific array number by json['streams'][1].each do |codec_name| and that errors.

Final output should return "mpeg2video"?

CodePudding user response:

This is what worked. Had to drill down through the Array and Hash to get to it.

((json[''].each { |j| j['streams'] })[0])["codec_name"]

CodePudding user response:

Since you appear to have an array of hashes in your JSON, you need to target the key codec_name. This should work:

# Assuming json_hash is a Hash that was returned by `JSON.parse()`
json_hash = { "streams": [ { "index": 0, "codec_name": "mpeg2video"} ] }
json_hash['streams'].each { |j| j['codec_name'] }

In this loop j is targeting the hash, and therefore you need j['codec_name']

  • Related