Page Menu
Home
Phabricator
Search
Configure Global Search
Log In
Files
F19511177
D8363.id19886.diff
No One
Temporary
Actions
View File
Edit File
Delete File
View Transforms
Subscribe
Mute Notifications
Award Token
Flag For Later
Size
1 KB
Referenced Files
None
Subscribers
None
D8363.id19886.diff
View Options
Index: src/utils/__tests__/PhutilUtilsTestCase.php
===================================================================
--- src/utils/__tests__/PhutilUtilsTestCase.php
+++ src/utils/__tests__/PhutilUtilsTestCase.php
@@ -504,4 +504,26 @@
}
}
+ public function testPhutilJSONDecode() {
+ $default = (object)array();
+
+ $cases = array(
+ '{}' => array(),
+ '[]' => array(),
+ '' => $default,
+ '"a"' => $default,
+ '{,}' => $default,
+ 'null' => $default,
+ '"null"' => $default,
+ '[1, 2]' => array(1, 2),
+ '{"a":"b"}' => array('a' => 'b'),
+ );
+
+ foreach ($cases as $input => $expect) {
+ $result = phutil_json_decode($input, $default);
+ $this->assertEqual($expect, $result, 'phutil_json_decode('.$input.')');
+ }
+ }
+
+
}
Index: src/utils/utils.php
===================================================================
--- src/utils/utils.php
+++ src/utils/utils.php
@@ -1056,3 +1056,23 @@
return $quantity * $factor;
}
+
+
+/**
+ * Decode a JSON dictionary, or return a default value if the input does not
+ * decode or does not decode into a dictionary.
+ *
+ * @param string A string which ostensibly contains a JSON-encoded list or
+ * dictionary.
+ * @param default? Optional default value to return if the string does not
+ * decode, or does not decode into a list or dictionary.
+ * @return mixed Decoded list/dictionary, or default value if string
+ * failed to decode.
+ */
+function phutil_json_decode($string, $default = array()) {
+ $result = @json_decode($string, true);
+ if (!is_array($result)) {
+ return $default;
+ }
+ return $result;
+}
File Metadata
Details
Attached
Mime Type
text/plain
Expires
Mon, Jan 12, 11:01 PM (3 d, 1 h ago)
Storage Engine
blob
Storage Format
Encrypted (AES-256-CBC)
Storage Handle
9206026
Default Alt Text
D8363.id19886.diff (1 KB)
Attached To
Mode
D8363: Add phutil_json_decode(), for convenience
Attached
Detach File
Event Timeline
Log In to Comment