summaryrefslogtreecommitdiff
diff options
context:
space:
mode:
authorUrban Müller2014-10-01 18:46:14 +0200
committerUrban Müller2014-10-01 18:51:00 +0200
commit95bb09069f31e99f5598cbceb3197f17c70ae919 (patch)
tree9d31a0bba317eb194c6a6e0e6c1aa520687a0c9f
parent33e8695833b94fd1c83e37d7c7de9ced4edbb673 (diff)
downloaditools-95bb09069f31e99f5598cbceb3197f17c70ae919.tar.gz
itools-95bb09069f31e99f5598cbceb3197f17c70ae919.tar.bz2
itools-95bb09069f31e99f5598cbceb3197f17c70ae919.zip
it::json_encode() and it::json_decode()
-rw-r--r--it.class16
-rwxr-xr-xtests/it.t3
2 files changed, 19 insertions, 0 deletions
diff --git a/it.class b/it.class
index f514537..e0916c3 100644
--- a/it.class
+++ b/it.class
@@ -1006,5 +1006,21 @@ static function pipe($cmd, $args = array())
return new it_pipe(is_string($cmd) ? array('cmd' => $cmd, 'args' => $args) : array('data' => $cmd));
}
+/**
+ * Encodes data to json with unescaped slahes, unescape unicode and on devel pretty printing
+ */
+static function json_encode($data)
+{
+ return json_encode($data, JSON_UNESCAPED_SLASHES | JSON_UNESCAPED_UNICODE | (it::is_devel() ? JSON_PRETTY_PRINT : 0));
+}
+
+/**
+ * Decodes json data and provides warning if failed
+ */
+static function json_decode($json)
+{
+ return ($data = json_decode($json)) === null && $json != 'null' ? it::error(array('title' => "invalid json", 'body' => $json)) : $data;
+}
+
}
?>
diff --git a/tests/it.t b/tests/it.t
index 4cf61c1..673b2d7 100755
--- a/tests/it.t
+++ b/tests/it.t
@@ -389,3 +389,6 @@ is(it::any2utf8("a💚b"), "a💚b", "it::any2utf8 correctly handles 4-byte utf-
is(it::any2utf8(array("foo", utf8_decode("bär"))), array("foo", "bär"), "any2utf8 on arrays");
is(it::any2utf8(array("foo", array(utf8_decode("bär")))), array("foo", array("bär")), "any2utf8 on recursive arrays");
is(it::any2utf8(array(1, true, false, null)), array(1, true, false, null), "any2utf8 should leave types alone");
+
+foreach (array($dummy, false, true, null, 1, "a", "Ä", "/", array()) as $var)
+ is(it::json_decode(it::json_encode($var)), $var);