ruby on rails - Can't get values from json stored in database -
i'm trying write app logs json msgs db. part got. problem comes getting json back. can't values it. i've tried raw msgs db , getting values ( json gem seems not see json) i've tried parse via .to_json , doesn't seem work either. maby have idea how it? in advance
table:
mjl_pk bigserial mjl_body text <- json 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, jsonadds $load_path << 'config' #requirements require 'sinatra' require 'active_record' require 'json' require 'jsonadds' require 'restclient' #class db class mjl < activerecord::base #table name self.table_name = "msg_json_log" #serialization serialize :properties, json #overwrite activerecord id "mjl_pk" def self.primary_key "mjl_pk" end end #get json msg , write db post '/logger' content_type :json #check if msg json if json.is_json?(params[:data]) #insert data db msg = mjl.create(:mjl_body => params[:data] ,:mjl_issuer => 'logger', :mjl_action => 'test', :mjl_object =>'obj') else #else return error puts "not json \n" + params[:data] end end #get json id = params[:id] '/json/:id' content_type :json #get json 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' json puts json_body['key'] puts json_body[0]['key'] end
output:
{ "key": "i value", "group": { "key2": "next value", "key3": "another one" }, "val1": "val" } ["{\n \"key\": \"i value\",\n \"group\": {\n \"key2\": \"next value\",\n \"key3\": \"another one\"\n },\n \"val1\": \"val\"\n}"] key <--empty value 'puts json_body[0]['key']'
i've created json log in project this, might 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 , ready 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 might you.
Comments
Post a Comment