Reputation: 828
JSON.parse(response, object_class: OpenStruct) rescue response
My rails application has above line of code which is causing an weird issue. Here response
is coming from an external API call and looks like following
"{\"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}"
WheneverI am running the app as a whole the result after JSON.parse() looks like the following:
"{\"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
fields are unexpected and '&'
are also messed up, weird thing is it's not happening when I am executing the code line by line from rails console.
I have fixed the issue by just doing JSON.parse(response).deep_symbolize_keys!
but still confused about the issue.
Upvotes: 2
Views: 150
Reputation: 5847
It would be easier to help if you included the implementation that results in the confusing result.
Anyway, it looks like to_json
is being called on the OpenStruct object somewhere:
> 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}}"
Upvotes: 0