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?
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.
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.
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.
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.
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
ActiveSupport::JSON.decode(string)
will decode that for you into a delicious consumable object on the server side.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With