MediaWiki  master
FormatJson Class Reference

JSON formatter wrapper class. More...

Static Public Member Functions

static decode ( $value, $assoc=false)
 Decodes a JSON string. More...
 
static encode ( $value, $pretty=false, $escaping=0)
 Returns the JSON representation of a value. More...
 
static parse ( $value, $options=0)
 Decodes a JSON string. More...
 
static stripComments ( $json)
 Remove multiline and single line comments from an otherwise valid JSON input string. More...
 

Public Attributes

const ALL_OK = self::UTF8_OK | self::XMLMETA_OK
 Skip escaping as many characters as reasonably possible. More...
 
const FORCE_ASSOC = 0x100
 If set, treat JSON objects '{...}' as associative arrays. More...
 
const STRIP_COMMENTS = 0x400
 If set, strip comments from input before parsing as JSON. More...
 
const TRY_FIXING = 0x200
 If set, attempt to fix invalid JSON. More...
 
const UTF8_OK = 1
 Skip escaping most characters above U+007F for readability and compactness. More...
 
const XMLMETA_OK = 2
 Skip escaping the characters '<', '>', and '&', which have special meanings in HTML and XML. More...
 

Static Private Attributes

static $badChars
 Characters problematic in JavaScript. More...
 
static $badCharsEscaped
 Escape sequences for characters listed in FormatJson::$badChars. More...
 

Detailed Description

JSON formatter wrapper class.

Definition at line 26 of file FormatJson.php.

Member Function Documentation

◆ decode()

static FormatJson::decode (   $value,
  $assoc = false 
)
static

Decodes a JSON string.

It is recommended to use FormatJson::parse(), which returns more comprehensive result in case of an error, and has more parsing options.

In PHP versions before 7.1, decoding a JSON string containing an empty key without passing $assoc as true results in a return object with a property named "_empty_" (because true empty properties were not supported pre-PHP-7.1). Instead, consider passing $assoc as true to return an associative array.

But be aware that in all supported PHP versions, decoding an empty JSON object with $assoc = true returns an array, not an object, breaking round-trip consistency.

See https://phabricator.wikimedia.org/T206411 for more details on these quirks.

Parameters
string$valueThe JSON string being decoded
bool$assocWhen true, returned objects will be converted into associative arrays.
Returns
mixed The value encoded in JSON in appropriate PHP type. null is returned if $value represented null, if $value could not be decoded, or if the encoded data was deeper than the recursion limit. Use FormatJson::parse() to distinguish between types of null and to get proper error code.

Definition at line 174 of file FormatJson.php.

References $value.

Referenced by BotPassword\__construct(), GitInfo\__construct(), ParserTestRunner\cleanupOption(), ChangesListSpecialPage\considerActionsForDefaultSavedQuery(), UpdateExtensionJsonSchema\execute(), ForeignAPIRepo\fetchImageQuery(), ImportSiteScripts\fetchScriptList(), AutoloadGenerator\generateJsonAutoload(), CommentStore\getCommentInternal(), Language\getGrammarTransformations(), FindHooks\getHooksFromOnlineDocCategory(), ForeignAPIRepo\getInfo(), MWRestrictions\newFromJson(), MediaWiki\Site\MediaWikiPageNameNormalizer\normalizePageName(), SwiftFileBackend\objectListing(), LocalisationCache\readJSONFile(), FormatJsonTest\testDecodeReturnType(), FormatJsonTest\testEmptyJsonKeyArray(), HTMLAutoCompleteSelectFieldTest\testGetAttributes(), ExtensionProcessorTest\testGlobalSettingsDocumentedInSchema(), and ApiMainTest\testPrinterParameterValidationError().

◆ encode()

static FormatJson::encode (   $value,
  $pretty = false,
  $escaping = 0 
)
static

Returns the JSON representation of a value.

Note
Empty arrays are encoded as numeric arrays, not as objects, so cast any associative array that might be empty to an object before encoding it.
In pre-1.22 versions of MediaWiki, using this function for generating inline script blocks may result in an XSS vulnerability, and quite likely will in XML documents (cf. FormatJson::XMLMETA_OK). Use Xml::encodeJsVar() instead in such cases.
Parameters
mixed$valueThe value to encode. Can be any type except a resource.
string | bool$prettyIf a string, add non-significant whitespace to improve readability, using that string for indentation. If true, use the default indent string (four spaces).
int$escapingBitfield consisting of _OK class constants
Returns
string|false String if successful; false upon failure

Definition at line 115 of file FormatJson.php.

References $options, and $value.

Referenced by JsonContent\beautifyJSON(), ApiFormatBase\closePrinter(), CommentStore\createComment(), FileBackendMultiWrite\doOperationsInternal(), FileBackendStore\doOperationsInternal(), Xml\encodeJsVar(), UpdateExtensionJsonSchema\execute(), WebInstallerName\execute(), ApiExpandTemplates\execute(), ListVariants\execute(), ApiParse\execute(), ApiFormatJson\execute(), RunJobs\execute(), ConvertExtensionToRegistration\execute(), GetConfiguration\execute(), JSONRCFeedFormatter\formatArray(), AutoloadGenerator\generateJsonAutoload(), MessageBlobStore\generateMessageBlob(), HTMLAutoCompleteSelectField\getAttributes(), HTMLTitleTextField\getDataAttribs(), HTMLFormField\getDiv(), HTMLFormField\getHelpTextHtmlDiv(), HTMLFormField\getHelpTextHtmlTable(), HTMLCheckMatrix\getTableRow(), HTMLFormField\getTableRow(), MWExceptionHandler\jsonSerializeException(), FileOp\logFailure(), BotPassword\newUnsaved(), SwiftFileBackend\onError(), Pingback\postPingback(), GitInfo\precomputeValues(), JsonContent\primitiveValue(), FileBackendMultiWrite\resyncFiles(), BotPassword\save(), FormatJsonTest\testEmptyJsonKeyArray(), FormatJsonTest\testEncodeAllOk(), FormatJsonTest\testEncodeDefault(), FormatJsonTest\testEncodeFail(), FormatJsonTest\testEncodePhpBug46944(), FormatJsonTest\testEncoderPrettyPrinting(), FormatJsonTest\testEncodeUtf8(), FormatJsonTest\testEncodeXmlMeta(), JsonContentTest\testFillParserOutput(), MWRestrictionsTest\testJson(), FormatJsonTest\testParse(), FormatJsonTest\testParseTryFixing(), MWRestrictions\toJson(), Job\toString(), GenerateJsonI18n\transformI18nFile(), and GenerateJqueryMsgData\writeJavascriptFile().

◆ parse()

static FormatJson::parse (   $value,
  $options = 0 
)
static

Decodes a JSON string.

Unlike FormatJson::decode(), if $value represents null value, it will be properly decoded as valid.

Parameters
string$valueThe JSON string being decoded
int$optionsA bit field that allows FORCE_ASSOC, TRY_FIXING, STRIP_COMMENTS
Returns
Status If valid JSON, the value is available in $result->getValue()

Definition at line 188 of file FormatJson.php.

References $code, $options, $value, StatusValue\newFatal(), StatusValue\newGood(), and wfMessage().

Referenced by JsonContent\getData(), ApiCSPReport\getReport(), FormatJsonTest\testParse(), FormatJsonTest\testParseErrors(), FormatJsonTest\testParseStripComments(), and FormatJsonTest\testParseTryFixing().

◆ stripComments()

static FormatJson::stripComments (   $json)
static

Remove multiline and single line comments from an otherwise valid JSON input string.

This can be used as a preprocessor, to allow JSON formatted configuration files to contain comments.

Parameters
string$json
Returns
string JSON with comments removed

Definition at line 259 of file FormatJson.php.

References $buffer, and string.

Referenced by FormatJsonTest\testStripComments().

Member Data Documentation

◆ $badChars

FormatJson::$badChars
staticprivate
Initial value:
= [
"\u{2028}",
"\u{2029}",
]

Characters problematic in JavaScript.

Note
These are listed in ECMA-262 (5.1 Ed.), §7.3 Line Terminators along with U+000A (LF) and U+000D (CR). However, PHP already escapes LF and CR according to RFC 4627.

Definition at line 85 of file FormatJson.php.

◆ $badCharsEscaped

FormatJson::$badCharsEscaped
staticprivate
Initial value:
= [
'\u2028',
'\u2029',
]

Escape sequences for characters listed in FormatJson::$badChars.

Definition at line 93 of file FormatJson.php.

◆ ALL_OK

◆ FORCE_ASSOC

const FormatJson::FORCE_ASSOC = 0x100

If set, treat JSON objects '{...}' as associative arrays.

Without this option, JSON objects will be converted to stdClass.

Since
1.24

Definition at line 63 of file FormatJson.php.

Referenced by ApiCSPReport\getReport(), and FormatJsonTest\testParse().

◆ STRIP_COMMENTS

const FormatJson::STRIP_COMMENTS = 0x400

If set, strip comments from input before parsing as JSON.

Since
1.25

Definition at line 77 of file FormatJson.php.

Referenced by FormatJsonTest\testParseStripComments().

◆ TRY_FIXING

const FormatJson::TRY_FIXING = 0x200

If set, attempt to fix invalid JSON.

Since
1.24

Definition at line 70 of file FormatJson.php.

Referenced by FormatJsonTest\testParseTryFixing().

◆ UTF8_OK

const FormatJson::UTF8_OK = 1

Skip escaping most characters above U+007F for readability and compactness.

This encoding option saves 3 to 8 bytes (uncompressed) for each such character; however, it could break compatibility with systems that incorrectly handle UTF-8.

Since
1.22

Definition at line 34 of file FormatJson.php.

Referenced by JsonContent\beautifyJSON(), Xml\encodeJsVar(), and FormatJsonTest\testEncodeUtf8().

◆ XMLMETA_OK

const FormatJson::XMLMETA_OK = 2

Skip escaping the characters '<', '>', and '&', which have special meanings in HTML and XML.

Warning
Do not use this option for JSON that could end up in inline scripts.
  • HTML 5.2, §4.12.1.3 Restrictions for contents of script elements
  • XML 1.0 (5th Ed.), §2.4 Character Data and Markup
Since
1.22

Definition at line 46 of file FormatJson.php.

Referenced by ApiFormatJson\execute(), and FormatJsonTest\testEncodeXmlMeta().


The documentation for this class was generated from the following file: