public
Created

JSON utility class

  • Download Gist
example.php
PHP
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16
<?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);
json.php
PHP
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56
<?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;
}
 
}

Please sign in to comment on this gist.

Something went wrong with that request. Please try again.