Re: JSON float number as string
| From: | Alexey Zakhlestin | Date: | Tue, 14 Apr 2015 06:33:38 +0000 |
| Subject: | Re: JSON float number as string | ||
| References: | 1 2 | Groups: | php.internals |
| Request: | Send a blank email to internals+get-85797@lists.php.net to get a copy of this message | ||
> On 14 Apr 2015, at 07:31, Alexey Zakhlestin <indeyets@gmail.com> wrote:
>
> Feels a bit hackish
> I think it is possible to introduce an overall better solution
>
> We can expose result of json-tokenizing as a tree of objects:
>
> JSON\Object
> JSON\Array
> JSON\String
> JSON\Number
> JSON\False
> JSON\True
> JSON\Null
>
> then, it would be possible to introduce any number of experimental userland implementations
> like the one proposed here
I decided to elaborate
<?php
namespace JSON;
abstract class Value
{
public function toJson();
public function toNative(); // this would do, whatever json_decode does
}
class Object extends Value implements \ArrayAccess, \IteratorAggregate
{
}
class Array extends Value implements \ArrayAccess, \IteratorAggregate
{
}
abstract class Literal extends Value
{
public function toString();
public function __toString()
{
return $this->toString();
}
}
class String extends Literal
{
}
class Number extends Literal
{
public function toInt();
public function toFloat();
}
class False extends Literal
{
}
class True extends Literal
{
}
class Null extends Literal
{
}
So, in case of Number, there would be a way to get the value the way it was stored in document using
toString(), use toInt() or toFloat() to get a value with possible precision loss or use toNative(),
which would be “smart” and return int or float using the same logic, which json_decode() uses
now.
It would work the other way round too. Object::toJson() would return json-representation of the
tree.