2
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.

Dev
  • 794
  • 1
  • 9
  • 21
  • Not sure I understand this question as "the result after `JSON.parse` would not "look like" that. What you have posted is a String which happens to be in JSON format; however that is not what the result of `JSON.parse` would be. Based on your initial code block the result would be an `OpenStruct`. Can you please provide more clarity as to what the implementation looks like that produces the output you are referencing? – engineersmnky Apr 28 '23 at 20:44

1 Answers1

0

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}}"
Arctodus
  • 5,743
  • 3
  • 32
  • 44