Adding default field such as timestamp to json when rendering in rails - ruby-on-rails

I am newbie in Ruby on rails and want to config render :json, always adds an extra field such as timestamp or version at the end of json response. Like this
{
//json data
"time_stamp" : 24312512341235
}
I think it might have better way to do that than adding parameter everytime calling render json
Thanks for helping

Just like html, you can have a layout for JSON responses.
Create a file app/views/layouts/application.json.jbuilder
and fill it with this:
json.merge! JSON.parse(yield)
json.time_stamp Time.now.to_i
Note that you need to make sure you always return a JSON Object and not an Array.

Related

Rails 4: render string field as JSON / hash

I have a Rails model in which one of the text fields contains a JSON string. While rendering it in views with JSON format (such as through index or show) I want to convert the string to a JSON hash. How can I do this with jbuilder or otherwise?
In general, how to apply a transform on a field by calling some function, before rendering it via jbuilder.
Of course, the naive solution is to build the JSON manually and use render json: my_json_here but I am looking for a better way.
Well a JSON is a string already... Maybe you want to convert it back to an object...
This will transform you string into a hash or array object.
JSON.parse(string)
If you want to make the other way around, transform you hash or array into a JSON string:
{ foo: 'bar' }.to_json # "{\"foo\":\"bar\"}"
EDIT: As you are looking for something more advanced, I recommend using the gem ActiveModelSerializer, where you create serializer objects that can be used to render ActiveModel data into any format, like JSON.
I think you could use "serialization" to do this where all of the conversion from JSON object to string and back is handled by ruby.
apidock

Saving data from a JSON response

I currently have a JSON response, fairly simple one. But I couldn't find a good guide or kicking off point for getting the JSON response and saving it within a model that I have e.g posts.
"Grab a JSON feed containing posts and save each one within the posts
table in rails"
Is there a simple way to do this with rails?
Any help is greatly appreciated.
Not a lot to work with...but let's assume the json string is represented by the variable json_str.
parsed = JSON.parse(json_str)
The parsed string should now essentially just be key value pairs like any other hash. To get the value, simply use the key.
parsed["some_key"]
Will return the value. To make your post from this, you can take the values you need and pass them in one by one, like so:
Post.create(some_value: parsed["some_key"], # etc)
Or, if all of your keys happen to share names with your attributes, you can pass the params all at once by saying:
post = Post.new(parsed)
and then calling:
post.save
Let me know if you have trouble.

Is it possible to run .to_json on a hash but not have it escape previously .to_json'ified strings?

We have a caching layer that stores json output of strings. I'd like to be able to put these strings into an array which I then transform to json via .to_json but it escapes all the previously encoded json. Is there a way to avoid this?
Here's a sample action to explain:
def index
a={name:"jon", email:"jon#domain.com"}.to_json
r={}
r[:users]=[]
r[:users] << a
render json: r.to_json
end
Outputs:
{"users":["{\"name\":\"jon\",\"email\":\"jon#domain.com\"}"]}
But I want:
{"users":["{"name":"jon","email":"jon#domain.com"}"]}
Though I am not showing it here, I'd be open to using ActiveModelSerializer (the 0.8 branch)
Edit
One possibility is doing a JSON.parse but obviously, that's a bit of a performance hit which I'd like to avoid.
You are converting a json object to another json object.. Try replacing
a={name:"jon", email:"jon#domain.com"}.to_json
by
a={name:"jon", email:"jon#domain.com"}

Posting a json array to rails server

I want to know how can I post json array directly to rails server. Say,
POST '/api/notes_bulk', HTTP/1.1
Content-Type: application/json
[{“content”:”content1”, “title”:”title1”}, {“content”:”content2”, “title”:”title2”}, {“content”:”content3”, “title”:”title3”}, {“content”:”content4”, “title”:”title4”}, {“content”:”content5”, “title”:”title5”}]
I did some search about it and all of the examples had some kind of key mapped to the array. While in my case, the json is an array at its top level.
How can I get the json data in the controller code? I notice that rails wraps this data with a "_json" key, but when I accessing it, it says
Unpermitted parameters: _json, ....
You can use that '_json' key to access data. To remove the warning you have to permit all the object keys from JSON array. In your case:
params.permit(_json: [:content, :title])
You cannot use the built-in params from Rails in this case but you can create your own parser:
def create
contents = JSON.parse(request.raw_post)
end
The contents variable will be the array that you posted.
i think the issue you are facing had got to do with strong parameters.
you need to allow json params in controller.
Use params.require(:object).permit( list of allowed params)
I think this might be late, but just post here since the question is unanswered and for future visitors.
You have to wrap you JSON string into an object. For example, you can construct you Json string such as
var contentArray = [{“content”:”content1”, “title”:”title1”}, {“content”:”content2”, “title”:”title2”}];
var contentObj = {contents: contentArray};
Before submiting it to Rails
jsonData = JSON.stringify(contentObj);
Access it in Rails controller:
myContentArray = params[:contents]

jRuby hash iteration newbie here

I am very new to rails in general and what I have is a hash being passed as json for one format and now I need to pass it to the view to work with but I have no idea how to iterate over the hash to make it work in the view as I need to do some type of each loop over it. Its a 2 dimensional hash dunno if that means anything or not.
edit
example
{"status":"successful","service_list":[{"service_name":"mySQL","status":"RUNNING","status_message":"No errors reported","host":"1"},{"service_name":"PHP","status":"RUNNING","status_message":"No errors reported","host":"1"},{"service_name":"APache","status":"RUNNING","status_message":"No errors reported","host":"1"},{"service_name":"Jetty","status":"RUNNING","status_message":"No errors reported","host":"1"}]}
This renders fine when I do it as JSON, but using the same thing to render it out in an HTML based view is where I am getting stuck
You have converted a Ruby has to a JSON hash, which is a Javascript format. In Ruby you would access a hash as follows:
hash = {"foo": "bar"}
puts hash["foo"] # This returns "bar"
JSON is similar to Ruby, and can be accessed in the same manner:
var hash = {"foo": "bar"};
alert(hash["foo"]); # This alerts "bar"
If you want to iterate through this collection in Javascript, you can use a for loop:
var data = {"status":"successful","service_list":[{"service_name":"mySQL","status":"RUNNING","status_message":"No errors reported","host":"1"},{"service_name":"PHP","status":"RUNNING","status_message":"No errors reported","host":"1"},{"service_name":"APache","status":"RUNNING","status_message":"No errors reported","host":"1"},{"service_name":"Jetty","status":"RUNNING","status_message":"No errors reported","host":"1"}]};
for(x=0;x<data["service_list"].length;x++) {
alert(data["service_list"][x]["service_name"]); # This returns "mySQL", ...
};
If you are wanting to convert this JSON object to a Ruby has you can call "JSON.parse" with your JSON string as an argument.

Resources