ruby-on-rails 如何解决json解析为OpenStruct时额外的`table`和`modifiable`合并问题

voj3qocg  于 2023-05-02  发布在  Ruby
关注(0)|答案(1)|浏览(186)

bounty已结束。回答此问题可获得+50声望奖励。赏金宽限期19小时后结束。Dev正在寻找一个答案从一个有信誉的来源

JSON.parse(response, object_class: OpenStruct) rescue response

我的rails应用程序有上面一行代码,这导致了一个奇怪的问题。这里的response来自外部API调用,如下所示

"{\"payable_amount\":80.0,\"qr_data\":{\"data\":\"upi://pay?pa=paytm-@paytm&&mc=&tr=&am=80&cu=INR&paytmqr=\",\"image\":\"+1OqeGDVfgX5Thh2X4Yf2P8B8/it24m51v9gAAAABJRU5ErkJggg==\"},\"transaction_id\":387400583,\"success\":true}"

每当我运行应用程序作为一个整体后,JSON的结果。parse()看起来像这样:

"{\"table\":{\"payable_amount\":80.0,\"qr_data\":{\"table\":{\"data\":\"upi://pay?pa=paytm-@paytm\\u0026\\u0026mc=5411\\u0026tr=\\u0026am=80\\u0026cu=INR\\u0026paytmqr=\",\"image\":\"+1OqeGDVfgX5Thh2X4Yf2P8B8/it24m51v9gAAAABJRU5ErkJggg==\"},\"modifiable\":true},\"transaction_id\":387400583,\"success\":true},\"modifiable\":true}"

tablemodifiable字段是意外的,'&'也是混乱的,奇怪的是,当我从rails控制台逐行执行代码时,它并没有发生。
我已经通过执行JSON.parse(response).deep_symbolize_keys!修复了这个问题,但仍然对这个问题感到困惑。

r6vfmomb

r6vfmomb1#

如果包含导致混淆结果的实现,将更容易提供帮助。
无论如何,看起来to_json在OpenStruct对象的某处被调用:

> response = "{\"payable_amount\":80.0,\"qr_data\":{\"data\":\"upi://pay?pa=paytm-@paytm&&mc=&tr=&am=80&cu=INR&paytmqr=\",\"image\":\"+1OqeGDVfgX5Thh2X4Yf2P8B8/it24m51v9gAAAABJRU5ErkJggg==\"},\"transaction_id\":387400583,\"success\":true}"
> parsed_response = JSON.parse(response, object_class: OpenStruct)
> parsed_response.to_json
=> "{\"table\":{\"payable_amount\":80.0,\"qr_data\":{\"table\":{\"data\":\"upi://pay?pa=paytm-@paytm\\u0026\\u0026mc=\\u0026tr=\\u0026am=80\\u0026cu=INR\\u0026paytmqr=\",\"image\":\"+1OqeGDVfgX5Thh2X4Yf2P8B8/it24m51v9gAAAABJRU5ErkJggg==\"}},\"transaction_id\":387400583,\"success\":true}}"

相关问题