Skip to content

Instantly share code, notes, and snippets.

@BenMorel
Created January 27, 2020 23:45
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save BenMorel/e588ad976a92ccd46ed4081fc2c1ef6e to your computer and use it in GitHub Desktop.
Save BenMorel/e588ad976a92ccd46ed4081fc2c1ef6e to your computer and use it in GitHub Desktop.
Simple canonicalization of a JSON string.
<?php
/**
* Simple canonicalization of a JSON string.
*
* - removes formatting
* - sorts object properties
*/
class JsonCanonicalizer
{
/**
* @param string $json
*
* @return string
*
* @throws \JsonException
*/
public static function canonicalize(string $json) : string
{
$data = json_decode($json, false, 512, JSON_THROW_ON_ERROR);
$data = self::doCanonicalize($data);
return json_encode($data, JSON_THROW_ON_ERROR);
}
/**
* @param mixed $data
*
* @return mixed
*/
private static function doCanonicalize($data)
{
if (is_object($data)) {
$data = (array) $data;
ksort($data);
foreach ($data as $key => $value) {
$data[$key] = self::doCanonicalize($value);
}
return (object) $data;
}
if (is_array($data)) {
foreach ($data as $key => $value) {
$data[$key] = self::doCanonicalize($value);
}
}
return $data;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment