0

Parse the JSON file in Ruby script and obtain value for "key"

My JSON file looks like

"terraform": [
    {
  "backend": [
    {
      "s3": [
        {
          "bucket": "terraform-dev",
          "dynamodb": "terraform_files",
          "encrypt": "true",
          "key": "Apple/Employee/Background/terraform.tfstate"
        }
      ]
     }
  ],
  "required_version": "~> 0.11.8"
}
] 

I tried writing this script in Ruby

#!/usr/bin/env ruby
require "json"
file = File.open "/Users/Test/conf.json"
data = JSON.load file
mykey= data['terraform'].first['backend']['s3']['key']
print mykey
file.close

Expected result: Apple/Employee/Background/terraform.tfstate

Error Message: no implicit conversion of String into Integer (TypeError)

2 Answers 2

1

Due to the structure of the conf.json where it has a composition of {} with a [], accessing every key by its name is difficult. So use mykey = data['terraform'][0]['backend'][0]['s3'][0]['key']

Here, terraform is a single object in {} which can be accessed by its name. It contains an array object [] which have to be accessed by index [0], since there is only one element. The same follows for the inner elements also. '{ } ' used for key-value pair Object and '[]' is used for Arrays with values in json.

and enclose the whole "terraform" in {} in conf.json.

Sign up to request clarification or add additional context in comments.

Comments

1

Hash#dig works for accessing arrays based in their index:

p hash.dig(:terraform, 0, :backend, 0, :s3, 0, :key)
# "Apple/Employee/Background/terraform.tfstate"

The plus is it returns nil if some intermediate step is nil:

p foo.dig(:terraform, 0, :backend, 0, :s3, 1, :key) # nil
p foo.dig(:terraform, 0, :backend, 0, :orale, 0, :key) # nil

2 Comments

I did not know that you could dig by index, so even though this didn't explain that the data structure was being accessed incorrectly, this is a valuable answer. Thank you for sharing this
Yes, that's in the docs g = { foo: [10, 11, 12] }; g.dig(:foo, 1) #=> 11. And yes, I didn't point that out, thanks!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.