40

I have a JSON string in rails as shown below:

[{"content":"1D","createdTime":"09-06-2011 00:59"},{"content":"2D","createdtime":"09-06-2011 08:00"}]

which are the objects of a class content with attributes content and created time.

I would like to convert this JSON string to its respective JSON object array so that I can run a loop and decode the JSON to its objects in rails. How can I achieve this?

3 Answers 3

70

You can use the json library json

You can then do:

jsonArray = [{"content":"1D","createdTime":"09-06-2011 00:59"},   
              {"content":"2D","createdtime":"09-06-2011 08:00"}]
objArray = JSON.parse(jsonArray)

In response to your comment, you can do this, as long as your JSON fits your model

objArray.each do |object|
  # This is a hash object so now create a new one.
  newMyObject = MyObject.new(object)
  newMyObject.save # You can do validation or any other processing around here.
end
6
  • Thanks a lot Jeremy.Will try it out and let you know.
    – rogerstone
    Jun 8, 2011 at 20:25
  • Thanks jeremy.It worked .But after I got the objArray.I tried doing ActiveSupport::JSON.decode(objArray[0]) .It gave me this error Type Error:can't convert hash to string
    – rogerstone
    Jun 9, 2011 at 9:06
  • There is no need, JSON parse already turned it into an array of Ruby objects.
    – Jeremy B.
    Jun 9, 2011 at 12:00
  • So if I do Content.new(objArray[0]) .Would it create the object?I wanted to insert the content object into the database..
    – rogerstone
    Jun 9, 2011 at 14:02
  • Your example of the string jsonArray gives me a syntax error when I copy and paste it into the rails console.
    – wuliwong
    Feb 18, 2013 at 21:05
41

ActiveSupport::JSON.decode(string) will decode that for you into a delicious consumable object on the server side.

2
  • 1
    I'm not sure what you're asking then if you already knew this.
    – Mario
    Jun 8, 2011 at 20:33
  • 1
    Didn't know how to convert from json string to json array in rails :-).Tat was my question
    – rogerstone
    Jun 8, 2011 at 20:36
0

If JavaScript code is internal then you can do this:

<script>
    var hives = <%[email protected]_safe%>;
</script>

Otherwise:

create hidden textarea and set @hives.html_safe as its value now you can get it in JavaScript as element's value as shown below:

In html.erb file

<%= text_area_tag :hives_yearly_temp, @hives.html_safe, { style: "display: none;"} %>

In js file

var hives = JSON.parse( $('#hives_yearly_temp').val() );

To run loop

for(key in hives) {
  alert( hives[key] );
}

Your Answer

Reminder: Answers generated by Artificial Intelligence tools are not allowed on Stack Overflow. Learn more

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

Not the answer you're looking for? Browse other questions tagged or ask your own question.