Git Product home page Git Product logo

json's Introduction

Json

Release License Code Quality Build

No Longer Maintained

This repository is no longer maintained, and is deprecated. Its use is highly discouraged.

We don't need yet another Json package, because neither there is a need for it, nor it provide a unique or useful feature. Let's focus on something that matters more, or at least on improving existing libraries, projects, etc. If you think it's a wrong decision (e.g. you are an active user of this library and can't find an alternative), please open an issue.

This repository should be considered of a showcase of what I've done. Feel free to switch to the branch develop, and guess what version 2.0.0 would look like, and think how it could ever solve a single problem.

An alternative to this library would be Webmozart Json.

What's it?

A component for your JSON data. Huh! Just that? No! Continue reading.

Why Json?

Performance

Note: Unfortunately, the library performance seems not to be scalable. A bright result of micro-optimizations. A result of focusing on what matters least. See #59 for more details.

Flexible

  • Json is not only for JSON data. So what? Many types are supported, including JSON strings, arrays, objects and scalars (+ null). Resources are not supported, and won't be supported (because of the standards).
  • Use methods regardless of the data type. Merging two objects? Actually.
  • Do anything, even if not provided by the class, using a callable. Alternatives? Extend from the class and define your own things. For sure, it will be easy in both cases.
  • Oh, what if an index does not exist? Exception. Parsing bad JSON data? Exception, again. Warnings and notices? Very rare cases.

Many Ways

Like JavaScript dots to get indexes, or native PHP arrays? Choose. Even with JavaScript-like indexes, you can pass the index to a method or you can use Json::index(). It is your decision.

Example

An example from PHPUnit source code:

function prettify(string $json): string {
    $decodedJson = \json_decode($json, true);

    if (\json_last_error()) {
        throw new Exception(
            'Cannot prettify invalid json'
        );
    }

    return \json_encode($decodedJson, \JSON_PRETTY_PRINT | \JSON_UNESCAPED_SLASHES);
}

Looks good, but it can be really better:

// use MAChitgarha\Component\Json

function prettify(string $jsonStr): string {
    return Json::new($jsonStr)->getAsJson(\JSON_PRETTY_PRINT | \JSON_UNESCAPED_SLASHES);
}

Advantages:

  • Handling different exceptions is easier. Not just getting "Cannot prettify invalid json". Get exception message based on the error happened. Debugging will be easier.
  • Less code. Looks prettier. One line. Besides, sometimes, you don't even need to define that method, use Json directly without a function overhead.

Good! What Do I Need?

Almost nothing. PHP7, the JSON extension that comes with PHP7 by default, and usually Composer.

Installing

Composer is there!

composer require machitgarha/json

Note: You can also clone the project and load the files in your own way. The recommended way is Composer, however.

Documentation

Note: The documentation is outdated, wrt to version 1.0.0+.

See the GitHub wiki.

Contribution?

Although the library is no longer maintained, but you can see contribution guidelines here.

json's People

Contributors

machitgarha avatar

Stargazers

 avatar

Watchers

 avatar

Forkers

nasstya

json's Issues

Add an options parameter for Json::get()

An $options parameter after $index in Json::get() and all its variants (i.e. Json::getAs*()) and an option in either JsonOpt or a new GetOpt class should be added, which:

  • GetOpt::STRICT: Throws an exception when the index does not exists.

This is the only option for now, but it may be added more options later.

Accepting bad indexes

When a bad index (e.g. an index as an array) passed to a method, instead of checking it to be either a string or an integer, a TypeError is thrown. Instead, a custom exception should be thrown.

Remove return type of Json::*Option*() methods

Removing the return types of Json::*Option*() methods (e.g. Json::setOptions()) causes extending the class to be easier, because of redeclaring these methods in the child class will be more suitable. Currently, sometimes it causes incompatibility with the parent class. Instead of setting return value type hint to self, it should be commented.

Allow passing an array as an index

Currently, it's only possible to pass a string or an integer as index in the methods. However, it's a good idea to allow arrays to be passed (but not objects, because of its overhead). In this case, all array elements must be checked to be either a string or an integer. A possible improve in this case would be directly passing the array to Json::findElementRecursive() without checking it and iterating it twice in Json::extractIndex().

Make almost all return self to return static in PHPDoc

Using of child class methods after calling a parent class method using fluent interface is a bit bad. For example:

class Json2 extends MAChitgarha\Component\Json
{
    public function copy() {}
}

$json = new Json2();
$json->set([""])->copy();

Calling Json2::copy() after Json::set() is valid, but IDEs will not show it because of the self return type. Using static would fix this issue.

Add JSON_* constants

Add PHP's JSON_* constants to the class, and make the possibility to add or remove them. For example, add the options before calling Json::getAsJson(), instead of passing options as arguments.

Define new methods on the fly

Currently, flexibility to do custom operations on the data is enough:

  1. Extending Json class and add some custom methods to it;
  2. Using anonymous classes to define methods on-the-fly;
  3. Using Json::do() method.

However, it would be a good feature to add some methods on the fly, like the following:

$json = new MAChitgarha\Component\Json();

$json->customMethod = function ($args) {
    // Doing something interesting here
};
$json->customMethod("arg", "uments");

Things to note:

  1. The on-the-fly method definition uses __set() to set a new method, and calling a defined method uses __call().
  2. Defining static methods is hard to implement, so it should be ignored. However, it should be considered.
  3. Trying to override an existing class method must try an exception (or error), and trying to call a non-existence method should try an error (i.e. should not be an exception).
  4. It should be a way of accessing other methods inside the closure. The instance of the class may be passed through an argument to the closure, or it may be bound inside the closure.
  5. It should be a way of accessing an element in data using an index. The element should be extracted and be passed as an argument to the closure.

Call other method within Json::do() method's callback

Calling other methods inside Json class from the callable of Json::do() should be considered. Currently, it is now possible to do that. As an example:

$json = new Json();

$json->do(function () use ($json) {
    // $json->something();
});

However, this could be improved; maybe using Closure::bind() or Closure::bindTo(). Also, undefined behaviours might happen:

$json = new Json([
    "something" => 10
]);

$json->do(function (&$value) use ($json) {
    // Change data completely, set it to a string
    $json->set("Something");

    // Nothing happens here!
    $value = 3;
}, "something");

I don't know if it is fault of PHP itself or Json class, however, this behaviour must be considered.

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    ๐Ÿ–– Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. ๐Ÿ“Š๐Ÿ“ˆ๐ŸŽ‰

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google โค๏ธ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.