I've got a bar graph that I'm trying to populate with a JSON response. I'm using Rails 5 with the built in JBuilder functionality.
Here is my code:
def graph_data
#customers = Customer.all
#graph_data = {graph_type: "Customer Growth"}
#months = {}
x = 5
while x >= 0
#months[x.months.ago.strftime("%B")] = current_account.customers.where(:created_at => x.months.ago.beginning_of_month..x.months.ago.end_of_month).count
x = x - 1
end
#graph_data[:months] = #months
puts #graph_data.to_json
end
The line puts #graph_data.to_json outputs the following text:
{"graph_type":"Customer Growth","months":{"November":0,"December":0,"January":0,"February":0,"March":0,"April":3}}
as I would expect.
However, when I output the actual JSON response in my graph_data.json.jbuilder file the output is
[["graph_type","Customer Growth"],["months",{"November":0,"December":0,"January":0,"February":0,"March":0,"April":3}]]
My goal was to get a response that looked more like this:
{"graph_type":"Customer Growth","months":["November":0,"December":0,"January":0,"February":0,"March":0,"April":3]}
but I don't know how to accomplish this with jBuilder.
Here are the contents of my graph_data.json.jbuilder file.
json.array! #graph_data
Thanks in advance.
In your jbuilder file, replace
json.array! #graph_data
to
json.graph_type #graph_data[:graph_type]
json.months #graph_data[:months]
Related
I'm using Barby to generate EAN13 Barcodes.
I'm getting the error: undefined method two_dimensional?' for "400000000000":String
The code i'm using in the controller:
def index
#barcode = getnumber
#barcode_voorbeeld = Barby::HtmlOutputter.new(#barcode)
#barcode_voorbeeld.to_html
end
def getnumber
Barcode.first.number
end
In the end what I want to accomplish is to get the last Barcode model and add + 1 to the number, so something like #barcode = getnumber + "1" and the result of this should be in this case 400000000001
thanks in advance.
#number = getnumber
#barcode = Barby::Code128B.new(#number)
#barcode_voorbeeld = Barby::HtmlOutputter.new(#barcode)
#barcode_voorbeeld.to_html
input = {"color"=>["red"],"size"=>["s","l"]}
json_obj = [{"color":"red","id":"123","size":"s","name":"test"},
{"color":"yellow","id":"124","size":"s","name":"test"},
{"color":"red","id":"125","size":"l","name":"test"}]
Output should be
output["red_s"] = {"color":"red","id":"123","size":"s","name":"test"}
output["red_l"] = {"color":"red","id":"125","size":"l","name":"test"}
output is the combinations of the input and a find on the json_obj.
How to get the output in rails?
I have the below script to get the combinations ie.red_s and red_l,
ary = input.map {|k,v| [k].product v}
output = ary.shift.product(*ary).map {|a| Hash[a]}
And
output[red_s]=json_obj.find{|h| h["color"] == "red" and h["size"] == "S"}
I don't want to have any hardcodings in code like color and size as above.
I think this should get you close to what you want.
Note the "ticks" around your json array object (what you had is not valid ruby)
The other issue is you would have to figure a better way to create the output hash key.
require 'json'
input = {"color"=>["red"],"size"=>["s","l"]}
output = {}
json_obj = '[{"color":"red","id":"123","size":"s","name":"test"},
{"color":"yellow","id":"124","size":"s","name":"test"},
{"color":"red","id":"125","size":"l","name":"test"}]'
found = JSON.parse json_obj
input.each_key do |key|
found = found.select { |item| input[key].include?(item[key]) }
end
puts found
found.each do |item|
output_key = ""
input.each_key do |key|
output_key = "#{item[key]}_" + output_key
end
output["#{output_key}"] = item.to_json
end
puts output
I'm trying to write app which logs json msgs to db. That part I got. The problem comes with getting that json back. I can't get values from it.
I've tried to get raw msgs from db and getting values from this ( json gem seems not to see it as json)
I've tried to parse it via .to_json , but it doesn't seem to work either. Maby you have some idea how to get it?
Thanks in advance
table:
mjl_pk bigserial
mjl_body text <- JSON is stored here
mjl_time timestamp
mjl_issuer varchar
mjl_status varchar
mjl_action varchar
mjl_object varchar
mjl_pat_id varchar
mjl_stu_id varchar
code:
#Include config catalog, where jsonadds is
$LOAD_PATH << 'config'
#Requirements
require 'sinatra'
require 'active_record'
require 'json'
require 'jsonadds'
require 'RestClient'
#Class for db
class Mjl < ActiveRecord::Base
#table name
self.table_name = "msg_json_log"
#serialization
serialize :properties, JSON
#overwrite ActiveRecord id with "mjl_pk"
def self.primary_key
"mjl_pk"
end
end
#Get json msg and write it to db
post '/logger' do
content_type :json
#Check if msg is json
if JSON.is_json?(params[:data])
#insert data into db
msg = Mjl.create(:mjl_body => params[:data] ,:mjl_issuer => 'LOGGER', :mjl_action => 'test', :mjl_object =>'obj')
else
#else return error
puts "Not a JSON \n" + params[:data]
end
end
#Get json with id = params[:id]
get '/json/:id' do
content_type :json
#Get json from db
json_body = Mjl.where(mjl_pk: params[:id]).pluck(:mjl_body)
puts json_body
json_body = json_body.to_json
puts json_body
#Get 'patientData' from json
puts json_body['key']
puts json_body[0]['key']
end
Output:
{
"key": "I am a value",
"group": {
"key2": "Next value",
"key3": "Another one"
},
"val1": "Val"
}
["{\n \"key\": \"I am a value\",\n \"group\": {\n \"key2\": \"Next value\",\n \"key3\": \"Another one\"\n },\n \"val1\": \"Val\"\n}"]
key
<--empty value from 'puts json_body[0]['key']'
I've also created a JSON Log in my project like this, this might help you...
In Controller
current_time = Time.now.strftime("%d-%m-%Y %H:%M")
#status_log = {}
#arr = {}
#arr[:status_id] = "2.1"
#arr[:status_short_desc] = "Order confirmed"
#arr[:status_long_desc] = "Order item has been packed and ready for shipment"
#arr[:time] = current_time
#status_log[2.1] = #arr
#status_log_json = JSON.generate(#status_log)
StoreStock.where(:id => params[:id]).update_all(:status_json => #status_log_json)
In View
#json_status = JSON.parse(ps.status_json) # ps.status_json contails raw JSON Log
= #json_status['2.1']['status_long_desc']
Hope this might help you.
when you are doing
json_body = Mjl.where(mjl_pk: params[:id]).pluck(:mjl_body)
you already have json
so no need doing
json_body = json_body.to_json
Since doing this you get the string representation of json, just remove that line and you will get all the values.
Finally I've found how to do it.
I saw explanation on JSON methods at:
from json to a ruby hash?
Code which works for me:
json_body = Mjl.where(mjl_pk: params[:id]).pluck(:mjl_body)
puts json_body
jparsed = JSON.parse(json_body[0])
puts jparsed['key']
My search returns this hash bellow
{"product"=>[{:title=>"It's All About Shoes Barbie Shoe Tree 2010 Hallmark Ornament"}, {:title=>"Iron Lady Bug Key Holder - Hide-A-Key"}]}
here is the loop and the code that generates the hash
id = "B003TM2IDS,B004X75EX4"
ids = id.split(',')
response = []
prod = Hash.new
product = Hash.new
#fetch product title from amazon
for aid in ids do
res = Amazon::Ecs.item_lookup(aid, { :response_group => "ItemAttributes"})
res.items.each do |item|
prod[:title] = item.get("ItemAttributes/Title")
end
# hash
product = {"product" => response.push(prod.dup)}
end
#loop to print the titles - Not working
product.each do |item_prod|
puts item_prod.title
end
I do get the
undefined method `title' for # (NoMethodError)
My question are:
Is the Product hash correct?
Is the loop correct?
I've done this millions of times but some reason I can't see the problem with this
Thanks a lot in advance
Do as below:
product["product"].each do |prod|
puts prod[:title]
end
product["product"].each { |p| puts p[:title] }
I do the following
my_hash = Hash.new
my_hash[:children] = Array.new
I then have a function that calls itself a number of time each time writing to children
my_hash[:children] = my_replicating_function(some_values)
How do I write without overwriting data that is already written ?
This is what the entire function looks like
def self.build_structure(candidates, reports_id)
structure = Array.new
candidates.each do |candidate, index|
if candidate.reports_to == reports_id
structure = candidate
structure[:children] = Array.new
structure[:children] = build_structure(candidates, candidate.candidate_id)
end
end
structure
end
Maybe this:
structure[:children] << build_structure(candidates, candidate.candidate_id)
structure[:children] << build_structure(candidates, candidate.candidate_id)