0

I need to extract only the value for 'admins' from this Json using Ruby :

JSON -

 {
    "Roles":[
        {
             "admins":[
                "me"
            ],
        "role":"cleanup"
        },
    {
        "admins":[
            "tester"
        ],
        "role":"create a mess"
    },
       ]

}

RUBY -

require 'json'
file = File.read('adminlist_Feb_2017.json')
thismonthlist=JSON.parse(file)
puts thismonthlist['admins']

Output - this gives me a blank output however if i change the last line to : puts thismonthlist['Roles']

it gives me everything. I just want the list of admins.

2 Answers 2

1

Try something like this

 thismonthlist[:Roles].flat_map { |role| role[:admins] }
 => ["me", "tester"] 
Sign up to request clarification or add additional context in comments.

Comments

0
admins = []
File.open('adminlist_Feb_2017.json', 'r') do |file|
  json = JSON.parse(file.read)
  admins = json["Roles"].flat_map{|role| role["admins"]}.uniq
end

admins
# => ["me", "tester"]

I open the file and process it in a block to ensure it's closed at the end. In the block I read the file content and parse the json string into a hash. Then I go through the "Roles" of the hash, grab the "admins" arrays and return it as one array only with Enumerable#flat_map. After I use Enumerable#uniq to return each admin only once.

2 Comments

Thanks,works like a charm! Just need to figure out how to remove leading spaces and general cleanup of 'admins' now. Much appreciated!
I mean remove leading spaces from the admins? Try: [" me ", " tester "].map{|admin| admin.strip} # => ["me", "tester"].

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.