judahnator/json-manipulator

A library for JSON string manipulation

v2.0.2 2019-01-15 16:10 UTC

README

pipeline status

What is this?

The short version is its a library that allows you to interact with JSON strings in a more OOP way.

Not as in decoding it, but as in making in place changes to a literal JSON string. See some of the examples below for more details.

Usage

There are two main classes you will be using.

  • \judahnator\JsonManipulator\JsonArray - Used for manipulating arrays
  • \judahnator\JsonManipulator\JsonObject - Used for working with objects

They are setup automatically when calling eachother. There is a factory function, \judahnator\JsonManipulator\load_json(), which will automatically create and return the relevant object for you.

For example:

<?php

use function judahnator\JsonManipulator\load_json;

$jsonString = '{"foo":"bar"}';
load_json($jsonString)->foo = 'baz';

echo $jsonString; 
// '{"foo":"baz"}'

You may also work with nested properties.

<?php

use function judahnator\JsonManipulator\load_json;

$jsonString = '{"foo":["bar","baz"]}';
$jsonObject = load_json($jsonString);
$jsonObject->foo[] = 'bong';

echo $jsonString; 
// '{"foo":["bar","baz", "bong"]}'

You can also add/remove objects and arrays freely.

<?php

use function judahnator\JsonManipulator\load_json;

$jsonObject = load_json();
$jsonObject->object = (object)['foo' => 'bar'];
$jsonObject->array = ['zero', 'one', 'two'];

echo $jsonObject; 
// {"object":{"foo":"bar"},"array":["zero","one","two"]}