Skip to content

Instantly share code, notes, and snippets.

@ircmaxell
Created September 6, 2013 13:38
Show Gist options
  • Star 4 You must be signed in to star a gist
  • Fork 3 You must be signed in to fork a gist
  • Save ircmaxell/6463913 to your computer and use it in GitHub Desktop.
Save ircmaxell/6463913 to your computer and use it in GitHub Desktop.
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