nette / utils

🛠 Lightweight utilities for string & array manipulation, image handling, safe JSON encoding/decoding, validation, slug or strong password generating etc.
https://doc.nette.org/utils
Other
1.98k stars 147 forks source link

`Json::encode` does not support the flag `JSON_HEX_AMP` #275

Closed iambrosi closed 2 years ago

iambrosi commented 2 years ago

Bug Description

Json::encode() will not escape ampersands (& to \u0026) when the JSON_HEX_AMP flag is used. Instead, it will pretty print the output. The cause is that Json::PRETTY is defined as 0b0010, which equals 2, the same value as the PHP constant JSON_HEX_AMP.

Escaping ampersands is helpful for embedding json data into HTML.

Steps To Reproduce

Compare the output of json_encode against the output of Nette\Utils\Json::encode() when using the flag JSON_HEX_AMP.

echo json_encode($urls, JSON_HEX_AMP);

// VS

echo Nette\Utils\Json::encode($urls, JSON_HEX_AMP);

Expected Behavior

Given the following array:

$urls = ['http://foo.com?a=b&b=c', 'http://bar.com?a=b&b=c&d=a%20e'];

Calling Nette\Utils\Json::encode($urls, JSON_HEX_AMP); should output:

["http:\/\/foo.com?a=b\u0026b=c","http:\/\/bar.com?a=b\u0026b=c\u0026d=a%20e"]

Instead, it outputs:

[
    "http://foo.com?a=b&b=c",
    "http://bar.com?a=b&b=c&d=a%20e"
]

Possible Solution

Change the value of Nette\Utils\Json::PRETTY to something that is not already mapped to a built-in JSON flag.

dg commented 2 years ago

The second parameter was not intended to be used for JSON_* constants, but for JSON::* constants. But I guess it could be modified to work with standard constants as well.