0

I create a JSON object in my html view using JSON.stringify(object) which outputs the following JSON object

{
 "0X1W6": "{\"type\":\"Hourly\",\"hr\":\"12\",\"min\":\"30\",\"every_hr\":\"5\"}",
  "Tk18f": "{\"type\":\"Daily\",\"hr\":\"12\",\"min\":\"30\",\"days_checked\":[1,4]}"
}

How do I convert this to a ruby object which would look something like this:

[
  { :type => 'Hourly', :hr => 12, :min => 30, :every_hr => 5}
  { :type => 'Daily', :hr => 12, :min => 30, :days_checked => [1,4]}
]

4 Answers 4

2
result = []

z = ActiveSupport::JSON.decode( '{
  "0X1W6": "{\"type\":\"Hourly\",\"hr\":\"12\",\"min\":\"30\",\"every_hr\":\"5\"}",
  "Tk18f": "{\"type\":\"Daily\",\"hr\":\"12\",\"min\":\"30\",\"days_checked\":[1,4]}"
}')

z.each_value do|i|
  x = {}
  ActiveSupport::JSON.decode(i).each{|k,v|
    x[k.to_sym] = (v.class == String && v.to_i.to_s == v) ? v.to_i : v
  }
  result << x
end
Sign up to request clarification or add additional context in comments.

Comments

2
{
 "0X1W6": "{\"type\":\"Hourly\",\"hr\":\"12\",\"min\":\"30\",\"every_hr\":\"5\"}",
  "Tk18f": "{\"type\":\"Daily\",\"hr\":\"12\",\"min\":\"30\",\"days_checked\":[1,4]}"
}.to_json

Comments

0

I'm assuming you are passing that JSON from JavaScript to your server. On the server, you can use the 'json' gem to parse JSON like so: o = JSON.parse json_string.

If you literally need the data structure combined (removing the keys 0X1W6 and Tk18f), you'll have to post-process your ruby hash into an array. Using the same technique, you can convert string keys into symbols.

1 Comment

JSON.parse json_string is parsing it to { 0X1W6 => "{ type : Hourly....} so the second hash is getting stored as string instead of a hash
0

When I understand correctly, you HAVE JSON and want a ruby hash. Within rails this can be done with ActiveSupport::Json.decode(json) while 'json' is a string. But this would not give you the exact results you are looking for, you would furthermore have to do:

ActiveSupport::Json.decode(json).values.symbolize_keys

I hope this helps.

2 Comments

I'm getting undefined method `symbolize_keys'
I assumed you were using rails which provides this method on Hash through activesupport. Without rails, you can either require this part of activesupport or symbolize the keys yourself like shown in Sector's post.

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.