nutools/lib/ulib/support/php/json_build.php

49 lines
1.2 KiB
PHP
Executable File

#!/usr/bin/php
<?php # -*- coding: utf-8 mode: php -*- vim:sw=2:sts=2:et:ai:si:sta:fenc=utf-8
function fix_value($value) {
if ($value === "true") return true;
elseif ($value === "false") return false;
elseif ($value === "null") return null;
else return $value;
}
function setp(&$array, $keys, $value) {
if (is_array($keys)) $keys = implode(".", $keys);
$keys = explode(".", $keys);
$last = count($keys) - 1;
$i = 0;
if ($array === null) $array = array();
$current =& $array;
foreach ($keys as $key) {
if ($i == $last) break;
if (!array_key_exists($key, $current)) $current[$key] = array();
if (!is_array($current[$key])) $current[$key] = array($current[$key]);
$current =& $current[$key];
$i++;
}
if ($key === "") {
$current[] = $value;
} else {
$current[$key] = $value;
}
}
$data = array();
$empty = true;
for ($i = 1; $i < $argc; $i++) {
$namevalue = $argv[$i];
if (preg_match('/(.*?)=(.*)/', $namevalue, $ms)) {
$name = $ms[1];
$value = fix_value($ms[2]);
setp($data, $name, $value);
} else {
$value = fix_value($namevalue);
$data[] = $value;
}
$empty = false;
}
$options = JSON_NUMERIC_CHECK;
if ($empty) $options += JSON_FORCE_OBJECT;
echo json_encode($data, $options);