Skip to content

Embed URL

HTTPS clone URL

Subversion checkout URL

You can clone with
or
.
Download ZIP
JSON utility class
<?php
require 'json.php';
$json = new JSON;
$json->foo->bar->baz = "foo";
$json->foo->biz = "test";
$json->baz = array();
$json->baz[1] = "testing";
$json->baz[2] = "this";
$json->baz[3] = "out!";
$j2 = JSON::fromJSON($json->toJSON());
var_dump($json, $j2);
<?php
class JSON implements JSONSerializable {
protected $data = array();
public function &__get($key) {
if (!isset($this->data[$key])) {
$this->data[$key] = new static;
}
return $this->data[$key];
}
public function __set($key, $value) {
$this->data[$key] = $value;
}
public function __isset($key) {
return isset($this->data[$key]);
}
public function __unset($key) {
unset($this->data[$key]);
}
public function jsonSerialize() {
return $this->data;
}
public function toJSON() {
return json_encode($this);
}
public static function fromJSON($json) {
$tmp = json_decode($json);
return self::parseJSONResult($tmp);
}
private static function parseJSONResult($json) {
if (is_object($json)) {
$obj = new static;
foreach (get_object_vars($json) as $key => $value) {
$obj->$key = self::parseJSONResult($value);
}
return $obj;
} elseif (is_array($json)) {
$ret = array();
foreach ($json as $key => $value) {
$ret[$key] = self::parseJSONResult($value);
}
return $ret;
}
return $json;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Something went wrong with that request. Please try again.