From 7c61258ec289cec41b5b153b4baf4b8c44a5e8ec Mon Sep 17 00:00:00 2001 From: Urban Müller Date: Thu, 2 Dec 2021 19:25:39 +0100 Subject: allow reading/writing of json in one go --- it.class | 6 ++++++ 1 file changed, 6 insertions(+) (limited to 'it.class') diff --git a/it.class b/it.class index 649c84a..5f66c70 100644 --- a/it.class +++ b/it.class @@ -1111,6 +1111,7 @@ static function mail($p) * @param $filename name of file to read or - for stdin * @param $p['keyval'] each line of the file is one tab-separated key/value pair, return assoc array * @param $p['lines'] return file as array of lines without newline + * @param $p['json'] return data json-decoded, set to "assoc" to get objects as assoc arrays */ static function file_get($filename, $p = array()) { @@ -1126,6 +1127,8 @@ static function file_get($filename, $p = array()) } else if ($p['lines']) $result = explode("\n", rtrim($data, "\n")); + else if ($p['json']) + $result = it::json_decode($data, ['assoc' => $p['json'] == "assoc", 'it_error' => ['title' => "bad json in $filename"]]); else $result = $data; } @@ -1139,6 +1142,7 @@ static function file_get($filename, $p = array()) * @param $data data to write, string by default * @param $p['keyval'] $data must be an assoc array and is written as tab-separated lines * @param $p['lines'] write array of lines, appending newline + * @param $p['json'] write array as json * @param $p['mkdir'] create parent directory (one level) * @param $p['cdist'] distribute saved file */ @@ -1150,6 +1154,8 @@ static function file_put($filename, $data, $p = array()) $data = implode("", it::map('"$k\t$v\n"', $data)); else if ($p['lines']) $data = count((array)$data) ? implode("\n", (array)$data) ."\n" : ""; + else if ($p['json']) + $data = it::json_encode($data); if ($p['mkdir'] && $filename != "-") @mkdir(dirname($filename)); -- cgit v1.2.3