Kylie
Kylie

Reputation: 11749

Why am I getting &quot when using json_encode

Im returning some json

$keywords = Auth::user()->keywords;
return json_encode($keywords);

Its returning something like this.

{"id":1,"response":"qwrewqrqw","alt_response":"","keyword":"L0F3LZ","user_id":221,"extra_charge":"$0.00","campaign_id":0,"type":"DEMO","responses":0,"next_billing_date":"2017-10-24","status":"active"}

How can I get it to just return regular JSON. I've never had this problem before. It actually just suddenly started happening, and I only noticed it, because my JSON.parse($keywords) failed. So I console logged it, and got what you see above.

Any ideas?

My current workaround so far is to just do...

 var data = JSON.parse(keywords.replace(/"/g,'"'));

Which works fine and gives me the object. But...if one field contains a space, or line break, then this breaks. How can I get regular old JSON instead of this &quot crap.

Upvotes: 3

Views: 2218

Answers (1)

ishegg
ishegg

Reputation: 9937

In Blade, the default behavior is to escape the characters. So when you do

{{ $yourJSON }}

it's escaping the quotes, causing the problem your having. To avoid this, change it to

{!! $yourJSON !!}

so it won't escape it, and you won't have a problem parsing the JSON.

The default behavior changed in Laravel 5 (it previously didn't escape by default), which might be why you experienced this all of a sudden.

Blade documentation

Upvotes: 6

Related Questions