I would like to return html content via jbuilder:
json.array!(#articles) do |article|
json.extract! article, :id, :title, :html_content
end
But it's returns escaped html:
{
"id": 2,
"title": "",
"html_content": "\u003cp\u003e\u003cimg alt=\"\" src=\"#\" /\u003e\u003c/p\u003e\r\n"
}
How can it return unescaped html?
You can use html_safe to disable the escape feature. Probably you run into some problems, because " won't be escaped as well and it's in use to define a value in JSON.
I think the best approach is to encode it somehow, for example with base64:
Base64 encode in ruby
Base64 decode in JavaScript
I believe the answer is to not retrieve the value via extract! I think this should do the trick.
json.array!(#articles) do |article|
json.extract! article, :id, :title
json.html_content article.html_content
end
Related
I'm building a practice Web API with Ruby + Sinatra and I want my responses to be displayed in a ERB template with formatted JSON (GeoJSON). So far I've been able to process the request and format the response correctly.
However, I can't find a way to display the contents in the endpoint as a JSON string, and it displays as a regular string (difficult to read for JSON). Is there any way to do that in Ruby + Sinatra without using JavaScript?
Here's what I've got so far in both files.
# app.rb
before do
json = File.open("data/cities.json").read
data = JSON.parse(json)
data.each do |item|
geoarray["features"].append(json_to_geojson(item))
end
#geojson = geoarray.to_json
end
...
get('/myendpoint') do
#activities = #geojson
erb :cities
end
<!--cities.erb-->
<%= #activities %>
try <%= #activities.to_json.html_safe %>
You can make JSON string look prettier by using JSON.pretty_generate() method.
# app.rb
before do
json = File.open("data/cities.json").read
data = JSON.parse(json)
data.each do |item|
geoarray["features"].append(json_to_geojson(item))
end
# use pretty_generate instead of to_json
#geojson = JSON.pretty_generate(geoarray)
end
And In your erb file. Instead of simple showing it, add <pre> tag to it.
<!--cities.erb-->
<pre><%= #activities %></pre>
reference
I've been able to set all of my content types to be JSON in a before block, but is there a sinatra after filter that allows me to run to_json on all of the responses (instead of writing to_json 3 times in my example below)?
require 'sinatra'
require 'json'
before do
content_type :json
end
get '/' do
{ song: "Hello" }.to_json
end
get '/go' do
{ song: "Go Yo Ho" }.to_json
end
get '/hi' do
{ song: "Wake me Up" }.to_json
end
Thanks!
You can do that in an after block:
before do
content_type :json
end
get '/' do
{ a: 1 }
end
after do
response.body = JSON.dump(response.body)
end
Sinatra will re-calculate the correct content length for the updated body value.
An alternate way would be to use a helper:
helper do
def j(data)
JSON.dump(data)
end
end
get '/' do
j({ a: 1 })
end
The Sinatra::JSON project does the same thing. Also, you might want to look at libraries designed for building APIs like Grape or Goliath. These two libraries provide a easy way to attach decoders and encoders to handle this type of automatic conversion.
Put set :default_content_type, 'application/json' and all your responses will include a Content-Type: application/json header.
I am sending data from puppet agent to master node. Here I use json array in my facters/facts.d/myData.json file. In master side I have a template. There I want to iterate this external fact json array.
{ "employees" :
[
{"firstName":"John", "lastName":"Doe"},
{"firstName":"Anna", "lastName":"Smith"},
{"firstName":"Peter", "lastName": "Jones"},
]
}
Can I do this thing inside puppet template ? How Can I iterate this array ? I tried following but failed
<% #employees.each do |firstname| -%>
malintha
<% end -%>
Regards,
Malintha
Your template is essentially a Ruby scriptlet. To operate on JSON data from your ruby code, you have to deserialize it into a bona fide Ruby object.
Note that your Array contains Hashes, so your template needs to be structured differently, anyway:
<% require 'json'
JSON.parse(#employees).each do |person|
firstname, lastname = person['firstName'], person['lastName'] -%>
<%= firstname %>
<% end -%>
I want an external webpage rates.appiclife.com to be rendered in the applications <%=yield%>.
I tried this:
I placed the following method in pages_controller.rb
def fetch_url(url)
r = Net::HTTP.get_response( URI.parse( url ) )
if r.is_a? Net::HTTPSuccess
r.body
else
nil
end
end
In the same file:
def showexternal
#snippet = fetch_url "http://rates.appiclife.com/"
end
And in the showexternal.html.erb view/pages:
<%= #snippet %>
I get the following error: incompatible character encodings: UTF-8 and ASCII-8BIT
Is it even possible to do this? The thing is that those prices are updated and received in an excel file, so a lot of work to adapt them if I just place them in a html-table.
You should be able to parse the request response with Nokogiri into a string and then do whatever you want to with it. You can find a quick tutorial here:
http://nokogiri.org/tutorials/parsing_an_html_xml_document.html
How can I display the following JSON object in Backbone View Template which I got with console.log?
Object {207: "402", 208: "400", 209: "402", 210: "0", 211: "0", 212: "50", 301: "401", 302: "400"}
I did use <% =207 %> and <% =208 %> in order to get value "402" and "400", but it didn't work.
Thank you very much for your help!
(edited)
Hi Vitaliy, are you still there? In this case I got from console.log, how can I print the value of "timestamp" and also "101"?
Object {timestamp: "2013-06-26T17:36:03+0530", values: Object}
timestamp: "2013-06-26T17:36:03+0530"
values: Object
101: "81"
102: "1500"
201: "49"
proto: Object
Thank you in advance!
You cannot use numbers as object keys. This is syntax error. Modify your object keys like that {"key_207": "402", ...}
Also to print result you should use <%= key_207 %> instead of <% =key_207 %>
The best way to fix this issue is to modify server response on the server side.
But also you can try do this (I'm not sure if it will work in all browsers):
var res = {207: "402", 208: "400"};
console.log(res[207]); // -> 402
So you need to pass your model to template inside some object and acces to key in the way above:
__template__({data:this.model.toJSON()})
And then:
<%= data[207] %>