ruby 如何将多维哈希值转换为JSON

qeeaahzv  于 12个月前  发布在  Ruby
关注(0)|答案(1)|浏览(85)

我的表列backend_notes中有一个哈希值,我需要将此哈希值更改为json格式。

{"school_id"=>"6", "accounts_response"=>"{\"type\"=>\"success\", \"message\"=>\"Updated Courses for 56789\"}", "courses
_not_found"=>"[{\"term\"=>\"FALL 2019\", \"dept_code\"=>\"ACCT\", \"dept_name\"=>\"ACCOUNTING\", \"course_code\"=>\"102\", \"course_name\"=>\"ELEM
ENTARY ACCT\", \"section_code\"=>\"000\", \"status\"=>\"new\", \"id\"=>20379}]"}

我尝试了下面的迁移命令将hash更改为json

change_column :carts, :backend_notes,'jsonb USING CAST(backend_notes AS jsonb)'

但这次迁移的形式是这样的。

{"school_id":"6", "accounts_response":"{\"type\"=>\"success\", \"message\"=>\"Updated Courses for 56789\"}", "courses
_not_found":"[{\"term\"=>\"FALL 2019\", \"dept_code\"=>\"ACCT\", \"dept_name\"=>\"ACCOUNTING\", \"course_code\"=>\"102\", \"course_name\"=>\"ELEM
ENTARY ACCT\", \"section_code\"=>\"000\", \"status\"=>\"new\", \"id\"=>20379}]"}

我的预期输出如下所示

{"school_id":"6","accounts_response":{"type":"success","message":"Updated Courses for 56789"},"courses_not_found":{"term":"FALL 2019","dept_code":"ACCT","dept_name":"ACCOUNTING","course_code":"102","course_name":"ELEMENTARY ACCT","section_code":"000","status":"new","id":"20379"}}
xtfmy6hx

xtfmy6hx1#

数据库中的哈希值包括Ruby对象的字符串表示(数组和哈希)。要将这些值完全转换为JSON,您需要首先将字符串转换为Ruby对象。
一个非常简单的方法可能是用:替换=>,并使用JSON解析器进行转换。这取决于内部结构,如果它工作,或者如果你需要更复杂的逻辑来修复这些值。我会从这样一个helper方法开始:

value = {"school_id"=>"6", "accounts_response"=>'{"type"=>"success", "message"=>"Updated Courses for 56789"}', "courses_not_found"=>'[{"term"=>"FALL 2019", "dept_code"=>"ACCT", "dept_name"=>"ACCOUNTING", "course_code"=>"102", "course_name"=>"ELEM ENTARY ACCT", "section_code"=>"000", "status"=>"new", "id"=>20379}]'}

# helper method
require 'json'

def string_parse_to_hash(string)
  modified_string = string
    .gsub(/:(\w+)/){"\"#{$1}\""}
    .gsub('=>', ':')
    .gsub("nil", "null")
  JSON.parse(modified_string)
rescue
  {}
end

# translate strings values to Ruby objects
value['accounts_response'] = string_parse_to_hash(value['accounts_response'])
value['courses_not_found'] = string_parse_to_hash(value['courses_not_found'])

value
#=> {
      "school_id"=>"6",
      "accounts_response"=>{"type"=>"success", "message"=>"Updated Courses for 56789"},
      "courses_not_found"=>[
        {"term"=>"FALL 2019",
          "dept_code"=>"ACCT",
          "dept_name"=>"ACCOUNTING",
          "course_code"=>"102",
          "course_name"=>"ELEM ENTARY ACCT",
          "section_code"=>"000",
          "status"=>"new",
          "id"=>20379
        }
      ]
    }

# translate to JSON
value.to_json
#=> "{\"school_id\":\"6\",\"accounts_response\":{\"type\":\"success\",\"message\":\"Updated Courses for 56789\"},\"courses_not_found\":[{\"term\":\"FALL 2019\",\"dept_code\":\"ACCT\",\"dept_name\":\"ACCOUNTING\",\"course_code\":\"102\",\"course_name\":\"ELEM ENTARY ACCT\",\"section_code\":\"000\",\"status\":\"new\",\"id\":20379}]}"

相关问题