Rails 有个 json 字段在数据库中供用户编辑,rails 如何传 json 格式到 controller

bill997603 · June 24, 2020 · Last by zhengpd replied at June 24, 2020 · 2237 hits
.setting-wrapper
  = form_for flow, as: :flow, url: [:admin, flow], remote: true do |f|
    = f.text_area :extra_rules, placeholder: '请输入 extra rules'

    .setting-actions.justify-between
      .left
      = f.submit '保存'
Parameters: {"utf8"=>"✓", "flow"=>{"extra_rules"=>"{one:1,two:2}"}, "commit"=>"保存", "id"=>"97"}

我现在从前端拿到的是字符串,没办法解析成 json

.to_json

JSON.parse(params["flow"]["extra_rules"])
Reply to hging

JSON::ParserError: 784: unexpected token at '{one:1,two:2}'

Reply to bill997603

这个不是一个 json 格式 合法的 json key 都是双引号括起来的

先加上双引号再处理:

begin
  str = "{one:1,two:2}"
  str.gsub!(/[\w|\p{Han}]+(?=:)/, '"\0"') # => "{\"one\":1,\"two\":2}"
  JSON.parse str
rescue JSON::ParserError
  # handle error
end
bill997603 closed this topic. 26 Jun 21:54
bill997603 reopened this topic. 26 Jun 21:54
bill997603 closed this topic. 26 Jun 21:54
You need to Sign in before reply, if you don't have an account, please Sign up first.