bln_dev
bln_dev

Reputation: 2411

Will php's json_encode() always use double quotes as string delimiter?

I have a php associative array containing strings as values and I encode it to JSON and store it in an html-data attribute. That is read by some JS.

So far so good.

Now, I need to use single quotes for the data attribute, otherwise the context switches.

<section id="settings" data-settings='{"some":"val"}'>
</section>

The question is, can I rely on the json_encode() function of php to encode strings always with double quotes? Surprisingly, I can't seem to find information on this. I only find articles from people having issues with quotes in the array values.

Thanks in advance.

Upvotes: 12

Views: 14482

Answers (2)

deceze
deceze

Reputation: 522015

Yes, as defined in the JSON spec, the delimiter will always be ". However, values may contain ' characters, which would break your HTML. To keep it simple and not worry about what might or mightn't pose an issue, HTML-escape your values!

<section data-settings="<?= htmlspecialchars(json_encode($foo)); ?>"></section>

This is guaranteed to work, always, no matter what values you pipe in or how you encode them.

NOTE that htmlspecialchars will by default only encode ", not '; so you must use " as the delimiter in HTML (or change the default escaping behavior).

Upvotes: 16

KmasterYC
KmasterYC

Reputation: 2354

Double-quotes is just convention - standard in JSON in many languagues. So if you want to store JSON in HTML attribute with double-quotes. You can encode that

In PHP

$encoded_json = base64_encode(json_encode($var));

In HTML

<section id="settings" data-settings='<?=$encoded_json?>'>

In JS

var variable = JSON.parse(atob(encoded_json));

Upvotes: 2

Related Questions