Ravindra Yadav
Ravindra Yadav

Reputation: 689

JSON parse Rails error

Hi I have a JSON data and there are some restrictions in JSON data to pass data in the same format (like string, JSON etc). below is my code:-

     buttons:[{
            type: "postback",
            title: p.name,
            payload: "get_product" 
     }]

here the payload key should be pass in the string but I have to pass some other keys also like product_id, name etc. so what I did is:-

     buttons:[{
            type: "postback",
            title: p.name,
            payload: "{'payload': 'get_product, 'product_id': #{p.id} }"
     }]

now when I will get the payload data then it is like this payload = "{'payload': 'get_product', 'product_id': d644bfda-2194-447c-b0f1-5d4f52c783a4 }" and when I parse the string to JSON and it throws error JSON.parse(payload) Processing by Messenger::Bot::Space::StationController#receive as */* *** JSON::ParserError Exception: 784: unexpected token at '{'payload': 'get_product', 'product_id': d644bfda-2194-447c-b0f1-5d4f52c783a4 }'.

I know the reason why its throws error because the payload data inside the single quotes so when I did it to payload = '{"payload": "get_product", "product_id": "d644bfda-2194-447c-b0f1-5d4f52c783a4" }' and when I did run JSON.parse(payload)

(byebug)

payload = '{"payload": "get_product", "product_id": "d644bfda-2194-447c-b0f1-5d4f52c783a4" }'

(byebug) JSON.parse(payload)

{"payload"=>"get_product", "product_id"=>"d644bfda-2194-447c-b0f1-5d4f52c783a4"}

But the issue is when I am using single quotes outside of the '{"payload": "get_product", "product_id" => #{p.id} }' then product_id key value not printed because of string interpolation so what should I do.

Upvotes: 0

Views: 1205

Answers (1)

Tom Lord
Tom Lord

Reputation: 28305

Instead of this:

"{'payload': 'get_product, 'product_id': #{p.id} }"

Do this:

{payload: 'get_product', product_id: p.id }.to_json

This will return something like:

"{\"payload\":\"get_product\",\"product_id\":123}"

...So as you can see, all the hard work like correctly escaping quotation marks is taken care of for you.

Upvotes: 1

Related Questions