Puppet : External facter json array iteration inside puppet template - json

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 -%>

Related

Rails How Can I Iterate Over JSON Field

I'm trying to play around with DALLĀ·E 2 and what I'm trying to do is simply call their image creation API and display the images using the image URLs they return.
I'm getting stuck on how to show the images on my web page based on the JSON response.
What I've done is save the response in a JSON attribute for my ImageRequest model.
So my code looks like this:
def new
#image_request = ImageRequest.new
end
def create
#image_request = ImageRequest.new(image_request_params)
client = OpenAI::Client.new(access_token: "my_key")
response = client.images.generate(parameters: { prompt: #image_request.prompt, n: #image_request.versions })
#image_request.urls = response
respond_to do |format|
if #image_request.save
format.html { redirect_to image_request_url(#image_request), notice: "Image request was successfully created." }
format.json { render :show, status: :created, location: #image_request }
else
format.html { render :new, status: :unprocessable_entity }
format.json { render json: #image_request.errors, status: :unprocessable_entity }
end
end
end
def show
#image_request = ImageRequest.find(params[:id])
end
But what I'm trying to determine is how can I parse and iterate the JSON and show the images?
# in psuedo code what I'm trying to do:
<% images.each do |i| %>
<%= image_tag "url" %>
<% end %>
This is what the OpenAI response is:
{
"created": 1674850160,
"data": [
{
"url": "https://oaidalleapiprodscus.blob.core.windows.net/private/...."
},
{
"url": "https://oaidalleapiprodscus.blob.core.windows.net/private/..."
}
]
}
When I look at the stored value in the JSON attribute (after create) in #image_request.urls, it's:
{"created"=>1674850160, "data"=>[{"url"=>"https://oaidalleapiprodscus.blob.core.windows.net..."}, {"url"=>"https://oaidalleapiprodscus.blob.core.windows.net/private/..."}]}
I've looked at these SO questions and experimented, but I can figure out how to just iterate through the data.url(s) returned.
Iterating over JSON in Rails
How do I parse JSON with Ruby on Rails?
Access JSONB fields as normal ActiveRecord attributes
Iterating over JSON in Rails
Loop through API response with .each
If response is {"created"=>1674850160, "data"=>[{"url"=>"https://oaida... then the JSON has already been parsed for you into a Ruby data structure. You then need to turn that into a list of URLs.
Pluck each "url" value from the Hashes in the "data" Array.
#image_request.urls = response["data"].pluck("url")
Now you have an Array of URLs which you can iterate through.
<% image_request.urls.each do |url| %>
<%= image_tag(url) %>
<% end %>

Display formatted JSON in HTML without JavaScript (Ruby, Sinatra)

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

Can I render JSON.parse data to EJS?

I am new to NodeJS and Express (to coding, in general). I am trying to render data to an EJS view page so I can manipulate it in the front end. It looks something like this:
app.set('view engine','ejs');
var str = JSON.parse('[{"name":"bill", "age":"26"}, {"name":"jeff", "age":"32"}]');
str.forEach(function(data){
console.log(data.name);
});
app.get('/data', function(req, res){
res.render('data', {str:str});
});
I try to test it in the EJS file by typing in <%= data %> the output I am getting in the browser is [object Object],[object Object]. I feel like I am missing a few piece. Can someone please help me out?
Thanks
Edit:
Thanks Booligoosh. Just want to add that I had to convert it back to JSON in the EJS side afterward to make it work. :)
You are attempting to print an array containing two objects to the ejs template. In a template you only print strings.
To print an object to the template we first need to stringify it:
<%= JSON.stringify(str) %>
To access a property of the object in your array we reference the array index and the property key:
<%= str[0].name %>
To iterate over the array and print out all the values we use a forEach:
<ul>
<% str.forEach(function(o) { %>
<li><%= o.name %> - <%= o.age %></li>
<% }); %>
</ul>
In ejs template we can render json object as below:
<%- JSON.stringify(user) %>
I tried with <%= JSON.stringify(user) %> (<%=) but it will print asci code values for double-quotes.
Try this:
app.set('view engine','ejs');
var str = JSON.parse('[{"name":"bill", "age":"26"}, {"name":"jeff", "age":"32"}]');
str.forEach(function(data){
console.log(data.name);
});
app.get('/data', function(req, res){
res.render('data', {str: JSON.stringify(str) });
});
You will need to convert your JSON object back to a string before passing it to the template using JSON.stringify, otherwise it will just be rendered with .toString, which returns [object Object],[object Object].

return unescaped html with jbuilder

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

Display JSON Object with numbers in Backbone.js Template

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] %>