82 public static function encode( $value, $pretty =
false, $escaping = 0 ) {
86 $options = JSON_UNESCAPED_SLASHES;
87 if ( $pretty || is_string( $pretty ) ) {
88 $options |= JSON_PRETTY_PRINT;
90 if ( $escaping & self::UTF8_OK ) {
91 $options |= JSON_UNESCAPED_UNICODE;
93 if ( !( $escaping & self::XMLMETA_OK ) ) {
94 $options |= JSON_HEX_TAG | JSON_HEX_AMP;
96 $json = json_encode( $value, $options );
98 if ( is_string( $pretty ) && $pretty !==
' ' && $json !==
false ) {
103 $json = preg_replace(
'/ {4}|.*+\n\K {4}/A', $pretty, $json );
132 public static function decode( $value, $assoc =
false ) {
133 return json_decode( $value, $assoc );
146 public static function parse( $value, $options = 0 ) {
147 if ( $options & self::STRIP_COMMENTS ) {
151 $result = json_decode( $value, $assoc );
152 $code = json_last_error();
154 if ( $code === JSON_ERROR_SYNTAX && ( $options & self::TRY_FIXING ) !== 0 ) {
163 preg_replace(
'/,([ \t]*[}\]][^"\r\n]*([\r\n]|$)|[ \t]*[\r\n][ \t\r\n]*[}\]])/',
'$1',
164 $value, -1, $count );
166 $result = json_decode( $value, $assoc );
167 if ( json_last_error() === JSON_ERROR_NONE ) {
169 $st = Status::newGood( $result );
170 $st->warning(
wfMessage(
'json-warn-trailing-comma' )->numParams( $count ) );
179 case JSON_ERROR_NONE:
180 return Status::newGood( $result );
182 return Status::newFatal(
wfMessage(
'json-error-unknown' )->numParams( $code ) );
183 case JSON_ERROR_DEPTH:
184 $msg =
'json-error-depth';
186 case JSON_ERROR_STATE_MISMATCH:
187 $msg =
'json-error-state-mismatch';
189 case JSON_ERROR_CTRL_CHAR:
190 $msg =
'json-error-ctrl-char';
192 case JSON_ERROR_SYNTAX:
193 $msg =
'json-error-syntax';
195 case JSON_ERROR_UTF8:
196 $msg =
'json-error-utf8';
198 case JSON_ERROR_INVALID_PROPERTY_NAME:
199 $msg =
'json-error-invalid-property-name';
201 case JSON_ERROR_UTF16:
202 $msg =
'json-error-utf16';
205 return Status::newFatal( $msg );
218 $str = (string)$json;
220 $maxLen = strlen( $str );
227 for ( $idx = 0; $idx < $maxLen; $idx++ ) {
228 switch ( $str[$idx] ) {
230 $lookBehind = ( $idx - 1 >= 0 ) ? $str[$idx - 1] :
'';
231 if ( !$inComment && $lookBehind !==
'\\' ) {
233 $inString = !$inString;
238 $lookAhead = ( $idx + 1 < $maxLen ) ? $str[$idx + 1] :
'';
239 $lookBehind = ( $idx - 1 >= 0 ) ? $str[$idx - 1] :
'';
243 } elseif ( !$inComment &&
244 ( $lookAhead ===
'/' || $lookAhead ===
'*' )
248 $buffer .= substr( $str, $mark, $idx - $mark );
253 $multiline = $lookAhead ===
'*';
255 } elseif ( $multiline && $lookBehind ===
'*' ) {
264 if ( $inComment && !$multiline ) {
280 return $buffer . substr( $str, $mark, $maxLen - $mark );
284class_alias( FormatJson::class,
'FormatJson' );
wfMessage( $key,... $params)
This is the function for getting translated interface messages.