Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 493
rogerstone Avatar asked Jun 08 '11 20:06

rogerstone


People also ask

How do I convert a string to an array in Ruby?

Strings can be converted to arrays using a combination of the split method and some regular expressions. The split method serves to break up the string into distinct parts that can be placed into array element. The regular expression tells split what to use as the break point during the conversion process.

How to use JSON parse in rails?

One way to use rails to parse json in a scalable and effective manner is to create a class that parses the JSON response and manages the data from the json fields using the object. The problem with this approach is we need to maintain the class and have to be clear on which fields are included in the JSON.

How JSON array looks like?

A JSON array contains zero, one, or more ordered elements, separated by a comma. The JSON array is surrounded by square brackets [ ] . A JSON array is zero terminated, the first index of the array is zero (0). Therefore, the last index of the array is length - 1.

How do you turn JSON into a Ruby object?

The most simplest way to convert a json into a Ruby object is using JSON. parse and OpenStruct class. If there are more subsequence keys after the response , the object. response will returns another instance of the OpenStruct class holding the subsequence methods as those subsequence keys.


2 Answers

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 
like image 70
Jeremy B. Avatar answered Sep 20 '22 14:09

Jeremy B.


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

like image 33
Mario Avatar answered Sep 17 '22 14:09

Mario