0

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.

2
  • have you tried payload: "{'payload': 'get_product, 'product_id': '#{p.id}' }" ? Commented Aug 18, 2017 at 13:10
  • Anyway, you're missing a single quote in payload: "{'payload': 'get_product, 'product_id': #{p.id} }" after get_product. Commented Aug 18, 2017 at 13:10

1 Answer 1

1

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.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.