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}"
table
&modifiable
字段是意外的,'&'
也搞砸了,奇怪的是,当我从rails控制台逐行执行代码时,它不会发生。
我已经通过做JSON.parse(response).deep_symbolize_keys!
修复了这个问题,但仍然对这个问题感到困惑。
如果您包含导致混乱结果的实现,将更容易提供帮助。
无论如何,看起来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}}"