JSON parse Rails error -


hi have json data , there restrictions in json data pass data in same format (like string, json etc). below code:-

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

here payload key should pass in string have pass other keys product_id, name etc. did is:-

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

now when payload data payload = "{'payload': 'get_product', 'product_id': d644bfda-2194-447c-b0f1-5d4f52c783a4 }" , when parse string json , throws error json.parse(payload) processing messenger::bot::space::stationcontroller#receive */* *** json::parsererror exception: 784: unexpected token @ '{'payload': 'get_product', 'product_id': d644bfda-2194-447c-b0f1-5d4f52c783a4 }'.

i know reason why throws error because payload data inside single quotes when did payload = '{"payload": "get_product", "product_id": "d644bfda-2194-447c-b0f1-5d4f52c783a4" }' , when 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 issue when using single quotes outside of '{"payload": "get_product", "product_id" => #{p.id} }' product_id key value not printed because of string interpolation should do.

instead of this:

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

do this:

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

this return like:

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

...so can see, hard work correctly escaping quotation marks taken care of you.


Comments

Popular posts from this blog

Is there a better way to structure post methods in Class Based Views -

performance - Why is XCHG reg, reg a 3 micro-op instruction on modern Intel architectures? -

jquery - Responsive Navbar with Sub Navbar -