100 public static function encode( $value, $pretty =
false, $escaping = 0 ) {
104 $options = JSON_UNESCAPED_SLASHES;
105 if ( $pretty || is_string( $pretty ) ) {
106 $options |= JSON_PRETTY_PRINT;
108 if ( $escaping & self::UTF8_OK ) {
109 $options |= JSON_UNESCAPED_UNICODE;
111 if ( !( $escaping & self::XMLMETA_OK ) ) {
112 $options |= JSON_HEX_TAG | JSON_HEX_AMP;
114 $json = json_encode( $value, $options );
116 if ( is_string( $pretty ) && $pretty !==
' ' && $json !==
false ) {
121 $json = preg_replace(
'/ {4}|.*+\n\K {4}/A', $pretty, $json );
150 public static function decode( $value, $assoc =
false ) {
151 return json_decode( $value, $assoc );
164 public static function parse( $value, $options = 0 ) {
165 if ( $options & self::STRIP_COMMENTS ) {
169 $result = json_decode( $value, $assoc );
170 $code = json_last_error();
172 if ( $code === JSON_ERROR_SYNTAX && ( $options & self::TRY_FIXING ) !== 0 ) {
181 preg_replace(
'/,([ \t]*[}\]][^"\r\n]*([\r\n]|$)|[ \t]*[\r\n][ \t\r\n]*[}\]])/',
'$1',
182 $value, -1, $count );
184 $result = json_decode( $value, $assoc );
185 if ( json_last_error() === JSON_ERROR_NONE ) {
187 $st = Status::newGood( $result );
188 $st->warning(
wfMessage(
'json-warn-trailing-comma' )->numParams( $count ) );
197 case JSON_ERROR_NONE:
198 return Status::newGood( $result );
200 return Status::newFatal(
wfMessage(
'json-error-unknown' )->numParams( $code ) );
201 case JSON_ERROR_DEPTH:
202 $msg =
'json-error-depth';
204 case JSON_ERROR_STATE_MISMATCH:
205 $msg =
'json-error-state-mismatch';
207 case JSON_ERROR_CTRL_CHAR:
208 $msg =
'json-error-ctrl-char';
210 case JSON_ERROR_SYNTAX:
211 $msg =
'json-error-syntax';
213 case JSON_ERROR_UTF8:
214 $msg =
'json-error-utf8';
216 case JSON_ERROR_INVALID_PROPERTY_NAME:
217 $msg =
'json-error-invalid-property-name';
219 case JSON_ERROR_UTF16:
220 $msg =
'json-error-utf16';
223 return Status::newFatal( $msg );
236 $str = (string)$json;
238 $maxLen = strlen( $str );
245 for ( $idx = 0; $idx < $maxLen; $idx++ ) {
246 switch ( $str[$idx] ) {
248 $lookBehind = ( $idx - 1 >= 0 ) ? $str[$idx - 1] :
'';
249 if ( !$inComment && $lookBehind !==
'\\' ) {
251 $inString = !$inString;
256 $lookAhead = ( $idx + 1 < $maxLen ) ? $str[$idx + 1] :
'';
257 $lookBehind = ( $idx - 1 >= 0 ) ? $str[$idx - 1] :
'';
261 } elseif ( !$inComment &&
262 ( $lookAhead ===
'/' || $lookAhead ===
'*' )
266 $buffer .= substr( $str, $mark, $idx - $mark );
271 $multiline = $lookAhead ===
'*';
273 } elseif ( $multiline && $lookBehind ===
'*' ) {
282 if ( $inComment && !$multiline ) {
298 return $buffer . substr( $str, $mark, $maxLen - $mark );
302class_alias( FormatJson::class,
'FormatJson' );
wfMessage( $key,... $params)
This is the function for getting translated interface messages.