使用mysql的Rails无法保存json数据类型

时间:2016-12-29 06:21:09

标签: mysql ruby-on-rails json

我用mysql(5.7.16)后端创建了Rails(3.2)应用程序。我无法保存json数据,并且我有如下传递值,它显示错误,如

  

ActiveRecord :: StatementInvalid - Mysql2 :: Error:无效的JSON文本:"无效的值。"列中的第1个值为shopping&cart_item_special_infos.special_info&#39 ;.:INSERT INTO shopping_cart_item_special_infos created_atshopping_cart_checkout_option_idspecial_infoupdated_at )VALUES(' 2016-12-29 06:08:52',141,' ---!ruby / hash:ActiveSupport :: HashWithIndifferentAccess \ n \' 201 \&# 39;:text1 \ n \' 209 \':\' 623 \' \ n \' 210 \':\' 625 \ ' \ n \' 211 \&#39 ;: text2 \ n',' 2016-12-29 06:08:52'):     activerecord(3.2.21)lib / active_record / connection_adapters / abstract_adapter.rb:285:in rescue in log' activerecord (3.2.21) lib/active_record/connection_adapters/abstract_adapter.rb:280:in log'     newrelic_rpm(3.9.1.236)lib / new_relic / agent / instrumentation / active_record.rb:63:in block in log_with_newrelic_i

{"201"=>"text1", "209"=>"623", "210"=>"625", "211"=>"text2"}

这里有什么问题?

2 个答案:

答案 0 :(得分:1)

您的JSON应该是这样的

{"201":"text1", "209":"623", "210":"625", "211":"text2"}

但是你传递了一个红宝石哈希

检查=>:

之间的区别

正如@ amruth-ls建议您可以在jsonlint

验证您的JSON

答案 1 :(得分:1)

最终我通过to_json方法

修复了上述错误

例)

{"201"=>"text1", "209"=>"623", "210"=>"625", "211"=>"text2"}.to_json

注意:我习惯使用to_json,因为我没有像使用

这样的代码将序列化值作为JSON
serialize :special_info, JSON

如果我使用上面的代码然后不需要使用as_json进行转换,它会自动将上面的数据解析为json数据,否则它会将数据视为字符串。