Skip to content
Dmitriy Zayceff edited this page May 31, 2015 · 3 revisions

To parse and format objects, arrays and primitives as JSON, you can use the php\format\JsonProcessor class instead of json_encode and json_decode. JPHP supports these php functions, add the jphp-zend-ext extension in your project to use them. To use the json class, you should add the jphp-json-ext extension.

How to parse JSON from a string?

use php\format\JsonProcessor;

$json = new JsonProcessor(JsonProcessor::DESERIALIZE_AS_ARRAYS);

$result = $json->parse('{"x": 10, "y": 20}');

var_dump($result); // array [x => 10, y => 20]

How to parse JSON from a file?

$jsonFile = Stream::of('path/to/file.json');

try {
   $result = $json->parse($jsonFile);
} finally {
   $jsonFile->close();
}

How to parse JSON from a URL?

Add the jphp-http-ext extension to use http and ftp sterams.

$jsonUrl = Stream:of('http://example.com/api/get.json');

try {
   $result = $json->parse($jsonUrl);
} finally {
   $jsonUrl->close();
}

How to convert an array/object to a JSON string?

$point = ['x' => 10, 'y' => 20];

$jsonString = $json->format($point);
echo $jsonString;

How to convert an array/object to a JSON file?

Use the jphp streams!

$point = ['x' => 10, 'y' => 20];

$output = Stream::of('path/to/file.json', 'w+'); // write mode.
try {
    $json->formatTo($point, $output);
} finally {
    $output->close();
}

How to convert to pretty JSON?

$json = new JsonProcessor(JsonProcessor::SERIALIZE_PRETTY_PRINT);
// ...
Clone this wiki locally