83 public static function encode( $value, $pretty =
false, $escaping = 0 ) {
87 $options = JSON_UNESCAPED_SLASHES;
88 if ( $pretty || is_string( $pretty ) ) {
89 $options |= JSON_PRETTY_PRINT;
91 if ( $escaping & self::UTF8_OK ) {
92 $options |= JSON_UNESCAPED_UNICODE;
94 if ( !( $escaping & self::XMLMETA_OK ) ) {
95 $options |= JSON_HEX_TAG | JSON_HEX_AMP;
97 $json = json_encode( $value, $options );
99 if ( is_string( $pretty ) && $pretty !==
' ' && $json !==
false ) {
104 $json = preg_replace(
'/ {4}|.*+\n\K {4}/A', $pretty, $json );
133 public static function decode( $value, $assoc =
false ) {
134 return json_decode( $value, $assoc );
147 public static function parse( $value, $options = 0 ) {
148 if ( $options & self::STRIP_COMMENTS ) {
152 $result = json_decode( $value, $assoc );
153 $code = json_last_error();
155 if ( $code === JSON_ERROR_SYNTAX && ( $options & self::TRY_FIXING ) !== 0 ) {
164 preg_replace(
'/,([ \t]*[}\]][^"\r\n]*([\r\n]|$)|[ \t]*[\r\n][ \t\r\n]*[}\]])/',
'$1',
165 $value, -1, $count );
167 $result = json_decode( $value, $assoc );
168 if ( json_last_error() === JSON_ERROR_NONE ) {
170 return Status::newGood( $result )->warning(
171 'json-warn-trailing-comma',
181 case JSON_ERROR_NONE:
182 return Status::newGood( $result );
185 case JSON_ERROR_DEPTH:
186 $msg =
'json-error-depth';
188 case JSON_ERROR_STATE_MISMATCH:
189 $msg =
'json-error-state-mismatch';
191 case JSON_ERROR_CTRL_CHAR:
192 $msg =
'json-error-ctrl-char';
194 case JSON_ERROR_SYNTAX:
195 $msg =
'json-error-syntax';
197 case JSON_ERROR_UTF8:
198 $msg =
'json-error-utf8';
200 case JSON_ERROR_INVALID_PROPERTY_NAME:
201 $msg =
'json-error-invalid-property-name';
203 case JSON_ERROR_UTF16:
204 $msg =
'json-error-utf16';
207 return Status::newFatal( $msg );
220 $str = (string)$json;
222 $maxLen = strlen( $str );
229 for ( $idx = 0; $idx < $maxLen; $idx++ ) {
230 switch ( $str[$idx] ) {
232 $lookBehind = ( $idx - 1 >= 0 ) ? $str[$idx - 1] :
'';
233 if ( !$inComment && $lookBehind !==
'\\' ) {
235 $inString = !$inString;
240 $lookAhead = ( $idx + 1 < $maxLen ) ? $str[$idx + 1] :
'';
241 $lookBehind = ( $idx - 1 >= 0 ) ? $str[$idx - 1] :
'';
245 } elseif ( !$inComment &&
246 ( $lookAhead ===
'/' || $lookAhead ===
'*' )
250 $buffer .= substr( $str, $mark, $idx - $mark );
255 $multiline = $lookAhead ===
'*';
257 } elseif ( $multiline && $lookBehind ===
'*' ) {
266 if ( $inComment && !$multiline ) {
282 return $buffer . substr( $str, $mark, $maxLen - $mark );
286class_alias( FormatJson::class,
'FormatJson' );