【问题标题】:Can't get values from json stored in database无法从存储在数据库中的 json 获取值
【发布时间】:2014-08-19 15:53:43
【问题描述】:

我正在尝试编写将 json msgs 记录到数据库的应用程序。我得到的那部分。问题在于获取该 json。我无法从中获得价值。 我试图从 db 获取原始 msgs 并从中获取值(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']'

【问题讨论】:

  • 您使用的是哪个数据库? PostgreSQL 9.3 有 JSON 数据类型,所以不需要序列化。
  • 我正在使用 postgresql,我已经尝试过了。但似乎 activerecord 没有得到它。当我从数据库中获取它时,它返回空值。除非我做错了什么。 (我使用与上面相同的代码)

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


【解决方案1】:

我还在我的项目中创建了这样的 JSON 日志,这可能会对您有所帮助...

在控制器中

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

希望这对你有帮助。

【讨论】:

    【解决方案2】:

    当你在做的时候

    json_body = Mjl.where(mjl_pk: params[:id]).pluck(:mjl_body)
    

    你已经有了 json 所以没必要做

     json_body = json_body.to_json
    

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

    【讨论】:

    • 感谢您的回答。我已经尝试过那个eariel(json_body ['key'])并且我得到了:没有将String隐式转换为Integer错误
    • 您能否提供完整的错误消息堆栈,或者它发生在哪一行?
    • 当然:C:/Users/r.leszczynski/workspace/nauka/app.rb in [] puts json_body['key'] C:/Users/r.leszczynski/workspace/nauka/app
      中的块中的 .rb 将 json_body['key'] C:/Ruby200/lib/ruby/gems/2.0.0/gems/sinatra-1.4.5/lib/sinatra/base.rb 放入调用 proc { |一个,p| unbound_method.bind(a).call } 我把它放在 json_body = Mjl.where(mjl_pk: params[:id]).pluck(:mjl_body)
    【解决方案3】:

    我终于找到了方法。
    我在以下位置看到了关于 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']
    

    【讨论】:

      猜你喜欢
      • 2016-08-16
      • 2020-05-20
      • 2010-11-13
      • 2020-07-25
      • 2021-11-04
      • 1970-01-01
      • 2018-05-27
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多