【问题标题】:Receiving a JSON string & saving one of the array paramaters to the database as a full string接收 JSON 字符串并将其中一个数组参数作为完整字符串保存到数据库中
【发布时间】:2010-05-04 05:26:05
【问题描述】:

您好,我有一个如下所示的 JSON 字符串(使用 Rails 和 REST 服务)

  {  
   person:   
      {
         name:"Pepe",
         last:"Smith"
         hats:[ { team:"lakers", color:"purple"}, { team:"heats", color:"red" }]   }   }

我希望能够获取该 JSON,并将 Person 保存到数据库中,但我想将“帽子”.. 作为字符串保存到数据库中;不解析它或类似的东西

即我想把它保存到 SQL:

hats = "[ { team:"lakers", color:"purple"}, { team:"heats", color:"red" }] }"

有没有办法在 Rails 中做到这一点?

【问题讨论】:

    标签: ruby-on-rails json rest


    【解决方案1】:

    在调用控制器操作之前,JSON 字符串会转换为 params 哈希。 您可以对hats 属性进行to_json 调用以获取等效的json 字符串。

    def create
      params[:person][:hats] = (params[:person][:hats]||{}).to_json
      p = Person.new(params[:person])
      if p.save
        #success
      else
        #error
      end
    end
    

    【讨论】:

      猜你喜欢
      • 2014-02-18
      • 1970-01-01
      • 1970-01-01
      • 2018-09-21
      • 2012-07-04
      • 2023-03-18
      • 1970-01-01
      • 1970-01-01
      • 2023-03-18
      相关资源
      最近更新 更多