Get data from JSON file into EJS variable - json

I want to get data from this JSON file: https://restcountries.com/v3.1/name/Poland into a EJS variable 'userData' and show it on the screen. How can I get it done?
I tried:
<%
const userData = require('https://restcountries.com/v3.1/name/Poland');
%>
<%= JSON.stringify(userData) %>

Related

Open JSON File in Rails and Stimulus

I have a select form which determines which values are shown in a table. The values are stored in a json file. My Question is: what is the best way to do this cuz i have a gut feeling smth might be wrong with my solution.
Im able to open the json file and save it in a json/jbuilder object in my controller and then call the object in my view and pass the json in the select which calls a stimulus function, which then handles what is shown on the table.
Main Controller:
class MainController < ApplicationController
def index
#itemsJSON = JSON.parse(File.read('db/data.json'))
end
end
Index View
<%= form_with do |form| %>
<%= form.select :city, [['all'], ['critical'],['error'],['warning'],['info'],['debug']],
{ prompt: "Select Item Type" },
data: { controller: "dropdownTable", value: #itemsJSON,
action: "change >dropdownTable#selectData"} %>
<% end %>
Stimulus Function
Code that doesnt work gives back error: localhost:8080/main/db/database.json not found which // i dont understand why
//fetch('/db/data.json')
// .then((response) => response.json())
// .then((json) => console.log(json));
export default class extends Controller {
selectData(event){
... code that works
}
}

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

cannot able to pass data from express to ejs?

i tried to pass a data from js file(sample.js) to ejs using res.send("filename.ejs",data) by converting a object into JSON where JSON data is displaying on console, but while trying to pass it showing an error
TypeError: Cannot create property '_locals' on string
can some one help with this and tell me how to call them in ejs file
res.send() is used for send data there is no need to point ejs file
res.send takes array as parameter (res.send([body])) and you can get it in ejs like {{ data }}
for example
NODEJS
res.send({message: 'hello'})
filename.ejs
<div>{{ message }}</div> or <%= JSON.stringify(message) %>
also as Express 5x does not support res.send() method you can use
res.status(200).send({message: 'hello})
(you did not admit you express version)
Note that you should not use the .ejs extension in res.render, despite other answers to your question suggesting that you do so.
When you call res.render('myView'), ejs looks for a template called myView.ejs in a folder called views (which is set as the default folder to use by ejs)
for example:
res.render('myView.ejs',{
data:data,
foo:'foo'
});
ejs will look for a view called myView.ejs.ejs (or it might just fail alltogether).
To access the data on your template, you would do the following:
app.js:
app.get('/somePathHere', function(req, res) {
res.render('myView',{
data:data,
foo:'foo'
});
});
myView.ejs:
<% data.forEach(function(item) { %>
//do something
<% }); %>
<%= foo %>
Note that when accessing a variable, you use the <%= varNameHere %>, and when writing any type of function, you would omit the =.
You're sending data to your view so update your code with this and try
res.render("filename",{
data:"hello"
});
Or you can pass whole data
res.render("filename",{data:data});
And in your ejs file access it like this
<div> <%= data %> <div>

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

Puppet : External facter json array iteration inside puppet template

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