无法从存储在数据库中的json获取值

时间:2014-08-18 08:11:20

标签: ruby-on-rails ruby json sinatra-activerecord

我正在尝试编写将json msgs记录到db的应用程序。那部分我得到了。问题来自于让json回归。我无法从中获取价值。 我试图从db获取原始消息并从中获取值(json gem似乎没有将其视为json) 我试图通过.to_json解析它,但它似乎也无法工作。 Maby你有一些想法如何得到它? 提前致谢

表:

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

代码:

#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

输出:

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

3 个答案:

答案 0 :(得分:1)

我也在这个项目中创建了一个JSON Log,这可能对你有帮助......

在控制器中

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)

在视图中

@json_status = JSON.parse(ps.status_json)  # ps.status_json contails raw JSON Log

= @json_status['2.1']['status_long_desc'] 

希望这对你有所帮助。

答案 1 :(得分:0)

当你做的时候

json_body = Mjl.where(mjl_pk: params[:id]).pluck(:mjl_body)
你已经有了json 所以不需要做

 json_body = json_body.to_json

由于这样做你得到json的字符串表示,只需删除该行,你就会得到所有的值。

答案 2 :(得分:0)

最后我发现了如何做到这一点。
我看到了JSON方法的解释:
from json to a ruby hash?
代码对我有用:

  json_body = Mjl.where(mjl_pk: params[:id]).pluck(:mjl_body)
  puts json_body
  jparsed = JSON.parse(json_body[0])
  puts jparsed['key']