Search code examples
ruby-on-railsrubyjsonsinatra-activerecord

Can't get values from json stored in database


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

Solution

  • 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']