rogerstone
rogerstone

Reputation: 7671

Convert JSON String to JSON Array in rails?

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?

Upvotes: 40

Views: 86945

Answers (3)

Taimoor Changaiz
Taimoor Changaiz

Reputation: 10684

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] );
}

Upvotes: 0

Jeremy B.
Jeremy B.

Reputation: 9216

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

Upvotes: 71

Mario
Mario

Reputation: 2942

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

Upvotes: 41

Related Questions