2017 © Pedro Peláez
 

library json

Encode, decode, validate, handle errors (exceptions) and pretty print JSON

image

hgg/json

Encode, decode, validate, handle errors (exceptions) and pretty print JSON

  • Wednesday, July 23, 2014
  • by hglattergotz
  • Repository
  • 1 Watchers
  • 1 Stars
  • 69 Installations
  • PHP
  • 0 Dependents
  • 0 Suggesters
  • 0 Forks
  • 0 Open issues
  • 2 Versions
  • 0 % Grown

The README.md

Json

Build Status, (*1)

Json is a collection of static methods to simplify working with JSON in PHP., (*2)

Features

  • encode to JSON string with error handling
  • decode from a string or file path containing valid JSON with error handling
  • validate a JSON document against a JSON Schema
  • pretty print a JSON string

Installation

The json-schema library version used here is currently a fork so you need to add the following to your composer.json file., (*5)

    "repositories": [
        {
            "type": "vcs",
            "url": "http://github.com/hglattergotz/json-schema"
        }
    ],

Dependencies

  • JsonPretty A Json pretty printer by Cam Spiers
  • JsonSchema A Json Schema validation library by Justin Rainbow

Usage

Encode

<?php

$data = array(
    'field' => 'value'
);

$jsonString = Json::encode($data);

Decode from string

Decode the contents of $jsonString as an associative array., (*6)

<?php

$data = Json::decode($jsonString, true);

Decode from file

Decode the contents of the file at $path as an associative array., (*7)

<?php

$data = Json::decode($path, true);

Pretty print

Note that the source can either be a JSON string or an array. The call below uses the default indentation of 2 spaces. To use a different indentation pass it as the second parameter., (*8)

<?php

$prettyJson = Json::prettyPrint($data);

Error handling

Instead of having to call json_last_error() and evaluating the integer response code the decode and encode methods throw an exception that contain the message as well as the code., (*9)

<?php

$invalidJson = '{';

try {
    $data = Json::decode($invalidJson);
} catch (HGG\Json\Exception\RuntimeException $e) {
    printf("Error message: %s\n", $e->getMessage());
    printf("Error code: %d\n", $e->getCode());
}

The code above example will output:, (*10)

Error message: JSON Error - Syntax error, malformed JSON
Error code: 4

The Versions

23/07 2014

dev-master

9999999-dev http://github.com/hglattergotz/json

Encode, decode, validate, handle errors (exceptions) and pretty print JSON

  Sources   Download

MIT

The Requires

 

The Development Requires

json validate encode decode exceptions error handling prettyprint json schema

23/07 2014

v0.1.0

0.1.0.0 http://github.com/hglattergotz/json

Encode, decode, validate, handle errors (exceptions) and pretty print JSON

  Sources   Download

MIT

The Requires

 

The Development Requires

json validate encode decode exceptions error handling prettyprint json schema