Display JSON Object with numbers in Backbone.js Template - json

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

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

Zapier Catch (Raw) Hook JSON parsing issue

I would like to configure sync between two different CRMs (Clevertap and Intercom) using Zapier and Webhooks. In general Clevertap sends the following JSON to webhook:
{
"targetId": 1548328164,
"profiles": [
{
"event_properties": {
"MSG-sms": true,
"MSG-push": true,
"businessRole": "EMPLOYEE",
"Mobile Number": "123123123123",
"Name": "Artem Hovtvianisa",
"Title": "Mr",
"Last Name": "Hovtvianisa",
"Gender": "M",
"Customer type": "Business Account Holder",
"MSG-email": true,
"First Name": "Artem",
"Last seen IP": "111.177.74.50",
"tz": "GMT+0200",
"International customer": "yes",
"isBusiness": true,
"Email": "xxxyyy#gmail.com",
"Identity": 15675
},
"objectId": "e32e4de3c1e84b2d9bab3707c92cd092",
"all_identities": [
"15675",
"xxxyyy#gmail.com"
],
"email": "xxxyyy#gmail.com",
"identity": "15675"
}
]
}
Zapier provides two types of catch webhook: regular and Raw.
Catch Raw Hook
When I use this type, JSON raw data will be handled OK and on the next step (Zapier JS code app) I am able to pass proper JSON data like in example above.
However when I use simple JS code to parse JSON object and get profiles[0] array value I get the following error "TypeError: Cannot read property '0' of undefined"
JS Code from Code step:
var result = JSON.parse(JSON.stringify(inputData));
console.log(result.profiles[0]);
return result;
Catch Hook
In case I use regular Catch Hook, hook parse data in some odd way, like this:
JSON.parse cannot recognize this structure.
Please advise how can I handle Webhook Zapier step in a proper way in order to get profiles[0] array item values?
Thanks in advance!
David here, from the Zapier Platform team. You're on the right track!
Catch Raw Hook is the way to go here. Your issue is that the data is coming in as a string and you're re-stringifying it before parsing it, which gets you back to where you came from. A simpler version:
JSON.stringify("asdf") // => "\"asdf\"", quotes in the string
JSON.parse("\"asdf\"") // => "asdf", the original string
"asdf".profiles // => undefined
undefined[0] // => error, cannot read property "0" of undefined
Instead, just parse it and you're good to go!
// all your variables are already in "inputData", so yours,
// also named inputData, must be referenced explicitly.
const result = JSON.parse(inputData.inputData);
return {result: result, firstProfile: result.profiles[0]};

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

Ignoring => when converting hash in ruby? How to properly convert hash?

I'm sending a post request, and this is the payload:
data = {updates: [{action: "create", user_id: "2", type: "view"}]}
but when I send it, the API says it was expecting:
{ action: \"create\", user_id: \"id\", type: \"type\" }
but it getting:
{:action=\u003e\\\"create\\\", :user_id=\u003e2\\\"2\\\", :type=\u003e\\\"view\\\"}\
The => is getting converted. I tried using to_json but that didn't help me.
How do I convert this properly? I think it has something to do with the nested array/hash because all the others work fine.
Also, I'm setting my request body and sending like so:
request.set_form_data(body)
https.request(request)
Looks like I need to use this syntax in order to pass set_form_data a nested hash:
{'a[b]': 'c'} is the same as {'a' => {'b' => 'c'}}
but is there a way to include the array? I need to have:
data = {updates: [{action: "create", user_id: "2", type: "view"}]}
in this notation.
As you mentioned, set_form_data does not accept arrays. It looks like a workaround if you wanted to continue using the Net::HTTP library is to encode the data and pass it to request.body.
request.body = "updates[][action]=create&updates[][type]=view&updates[][user_id]=2"
request.content_type = 'application/x-www-form-urlencoded'
You could also create a custom function like they did in this post: http://cloudlines.tumblr.com/post/653645115/postput-arrays-with-ruby-nethttp-setformdata
Check out this post on changing complex objects into a querystring: https://coderwall.com/p/uh8kiw/pass-arrays-objects-via-querystring-the-rack-rails-way.
Hope that helps!

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