PHP code example of pakman / json-parser

1. Go to this page and download the library: Download pakman/json-parser library. Choose the download type require.

2. Extract the ZIP file and open the index.php.

3. Add this code to the index.php.
    
        
<?php
require_once('vendor/autoload.php');

/* Start to develop here. Best regards https://php-download.com/ */

    

pakman / json-parser example snippets


$json = '{"foo": {"a": "1", "b": "str", "c": "2.1", "d": ["1", "2"], "e": {"a": "1"}}, "bar": "8 (950) 288-56-23"}';

$typeDefinitions = TypeDefinitions::define()
    ->object('foo', TypeDefinitions::define()
        ->integer('a')
        ->string('b')
        ->float('c')
        ->array('d', TypeDefinitions::INTEGER)
        ->object('e', TypeDefinitions::define()->integer('a'))
    )
    ->phone('bar')
;
$parser = new JsonParser($typeDefinitions);
$result = $parser->parse($json);

var_dump($result);

array(4)
  'foo' => 
    array(4)
      'a' => int(1)
      'b' => string(3) "str"
      'c' => float(2.1)
      'd' => 
        array (2)
          0 => int(1)
          1 => int(2)
      'e' => 
        array(1)
          'a' => int(1)
  'bar' => string(11) "79502885623"

    ...
    use pakman\jsp\parsers\Parser;
    
    class HelloWorldParser extends Parser {
    
        public function parse($data): array {
            if ($data !== 'Hello') {
                throw new ValidationException();
            }
    
            return $data . ' world!';
        }
    }
    

    ...
    use path\to\HelloWorldParser;
    
    return [
        ...
        'HELLO_WORLD_TYPE' => 'HelloWorldParser::class'
    ];
    

    $json = '{"foo": {"Hello"}}';
    
    $typeDefinitions = TypeDefinitions::define()
        ->add('foo', 'HELLO_WORLD_TYPE')
    ;
    $parser = new JsonParser($typeDefinitions);
    $result = $parser->parse($json);
    
    var_dump($result);

    // array(1)
    //   'foo' => string(12) "Hello world!"
    
src/config/parsers.php