1

I am saving one field as string in my model, so after that i tried via console

1.9.3-p547 :250 > s1 = s.send_details

 => "---\nnew_order: order\nprogress: order  on d way\ndelivered:\n  
message: delivered\n  send_after: '1'\n"

1.9.3-p547 :255 > JSON.parse(s1)
JSON::ParserError: 757: unexpected token at '---

'

1.9.3-p547 :262 > s1.class
=> String

i am trying to convert this to json or hash, because i need to take the values from that, is there any way to do this?

2
  • 1
    You can't with that string. Try too look at method before this call, and try to set send_details with a json or a hash, instead of parsing it afterwards. Commented Feb 3, 2015 at 14:36
  • 1
    Adding serialize :send_details to the model should serialize (and deserialize) the attribute automatically, see api.rubyonrails.org/classes/ActiveRecord/AttributeMethods/… Commented Feb 3, 2015 at 14:40

1 Answer 1

5

Looks like your string is a YAML. You can easy decode it with YAML.load:

require 'yaml'
YAML.load("---\nnew_order: order\nprogress: order  on d way\ndelivered:\n  message: delivered\n  send_after: '1'\n")
=> {"new_order"=>"order", "progress"=>"order  on d way", "delivered"=>{"message"=>"delivered", "send_after"=>"1"}}
Sign up to request clarification or add additional context in comments.

3 Comments

Thanks you so much grych, i just want to know something, why didn't take that filed value as string, in the model the data type of that filed is text in postgresql?
Probably that field was serializable. That means that you can write any object you want. In database, it is coded with YAML. Try do make this field serializable in the model, so when you will read it, you'll get the Hash in return.
Thanks grych for the comment

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.