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?

Deepak Mahakale
  • 22,834
  • 10
  • 68
  • 88
rogerstone
  • 7,541
  • 11
  • 53
  • 62

3 Answers3

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
Jeremy B.
  • 9,168
  • 3
  • 45
  • 57
  • Thanks a lot Jeremy.Will try it out and let you know. – rogerstone Jun 08 '11 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 09 '11 at 09:06
  • There is no need, JSON parse already turned it into an array of Ruby objects. – Jeremy B. Jun 09 '11 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 09 '11 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 '13 at 21:05
  • It's the extra quotes around the array. jsonArray should be an array not a string, I've fixed the answer. – Jeremy B. Feb 22 '13 at 16:31
41

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

Mario
  • 2,942
  • 1
  • 25
  • 38
0

If JavaScript code is internal then you can do this:

<script>
    var hives = <%=@hives.html_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] );
}
Taimoor Changaiz
  • 10,250
  • 4
  • 49
  • 53