Antarr Byrd
Antarr Byrd

Reputation: 26091

Parsing string to hash in ruby

I'm trying to parse a string in ruby to a hash but I can't quite figure it out. I've gotten it to a nested array just need to map it to the hash.

example string

subject = "{\"CN\"=\"schoen.io\", \"C\"=\"US\", \"ST\"=\"Texas\", \"L\"=\"North Doyle\", \"O\"=\"SSL Corporation\", \"OU\"=\"Information Technology Department\", \"2.5.4.17\"=\"16039-4645\", \"2.5.4.9\"=\"8268 Kemmer Village\", \"2.5.4.42\"=\"Tracy\", \"2.5.4.4\"=\"Jacobi\", \"2.5.4.5\"=\"grbh52f84senk4jkgo9n9a66yg62w78y4a0v36ax8tfacdshublxjpq6arcn7qyx\", \"2.5.29.17\"=\"ssl.com\"}}"

desired hash

{'CN' => 'schoen.io', 'C' => 'US', 'ST' => 'Texas',... }

my code

subject.gsub('{','').gsub('}','').split(',').map { |m| m.split('=')}

generated array

[["\"CN\"", "\"schoen.io\""], [" \"C\"", "\"US\""], [" \"ST\"", "\"Texas\""], [" \"L\"", "\"North Doyle\""], [" \"O\"", "\"SSL Corporation\""], [" \"OU\"", "\"Information Technology Department\""], [" \"2.5.4.17\"", "\"16039-4645\""], [" \"2.5.4.9\"", "\"8268 Kemmer Village\""], [" \"2.5.4.42\"", "\"Tracy\""], [" \"2.5.4.4\"", "\"Jacobi\""], [" \"2.5.4.5\"", "\"grbh52f84senk4jkgo9n9a66yg62w78y4a0v36ax8tfacdshublxjpq6arcn7qyx\""], [" \"2.5.29.17\"", "\"ssl.com\""]]

Upvotes: 1

Views: 77

Answers (1)

BTL
BTL

Reputation: 4656

I think you have a typo in you original subject. You have two } at the end of your string and only one at the beginning.

If you remove it your string is now :

subject = "{\"CN\"=\"schoen.io\", \"C\"=\"US\", \"ST\"=\"Texas\", \"L\"=\"North Doyle\", \"O\"=\"SSL Corporation\", \"OU\"=\"Information Technology Department\", \"2.5.4.17\"=\"16039-4645\", \"2.5.4.9\"=\"8268 Kemmer Village\", \"2.5.4.42\"=\"Tracy\", \"2.5.4.4\"=\"Jacobi\", \"2.5.4.5\"=\"grbh52f84senk4jkgo9n9a66yg62w78y4a0v36ax8tfacdshublxjpq6arcn7qyx\", \"2.5.29.17\"=\"ssl.com\"}"

You just need to do : JSON.parse(subject.gsub('=',':'))

And you will get the desired output :

{
 "CN"=>"schoen.io",
 "C"=>"US",
 "ST"=>"Texas",
 "L"=>"North Doyle",
 "O"=>"SSL Corporation",
 "OU"=>"Information Technology Department",
 "2.5.4.17"=>"16039-4645",
 "2.5.4.9"=>"8268 Kemmer Village",
 "2.5.4.42"=>"Tracy",
 "2.5.4.4"=>"Jacobi",
 "2.5.4.5"=>"grbh52f84senk4jkgo9n9a66yg62w78y4a0v36ax8tfacdshublxjpq6arcn7qyx",
 "2.5.29.17"=>"ssl.com"
}

Upvotes: 5

Related Questions