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