在线时间:8:00-16:00
迪恩网络APP
随时随地掌握行业动态
扫描二维码
关注迪恩网络微信公众号
开源软件名称:webmozart/json开源软件地址:https://github.com/webmozart/json开源编程语言:PHP 100.0%开源软件介绍:Webmozart JSONLatest release: 1.2.2 A robust wrapper for InstallationUse Composer to install the package:
EncodingUse the use Webmozart\Json\JsonEncoder;
$encoder = new JsonEncoder();
// Store JSON in string
$string = $encoder->encode($data);
// Store JSON in file
$encoder->encodeFile($data, '/path/to/file.json'); By default, the JSON schema stored in the use Webmozart\Json\ValidationFailedException;
try {
$string = $encoder->encode($data, '/path/to/schema.json');
} catch (ValidationFailedException $e) {
// data did not match schema
} DecodingUse the use Webmozart\Json\JsonDecoder;
$decoder = new JsonDecoder();
// Read JSON string
$data = $decoder->decode($string);
// Read JSON file
$data = $decoder->decodeFile('/path/to/file.json'); Like use Webmozart\Json\ValidationFailedException;
try {
$data = $decoder->decodeFile('/path/to/file.json', '/path/to/schema.json');
} catch (ValidationFailedException $e) {
// data did not match schema
} ValidationSometimes it is necessary to separate the steps of encoding/decoding JSON data
and validating it against a schema. In this case, you can omit the schema
argument during encoding/decoding and use the use Webmozart\Json\JsonDecoder;
use Webmozart\Json\JsonValidator;
use Webmozart\Json\ValidationFailedException;
$decoder = new JsonDecoder();
$validator = new JsonValidator();
$data = $decoder->decodeFile('/path/to/file.json');
// process $data...
$errors = $validator->validate($data, '/path/to/schema.json');
if (count($errors) > 0) {
// data did not match schema
} Note: This does not work if you use the SchemasYou are encouraged to store the schema of your JSON documents in the
{
"$schema": "http://example.org/schemas/1.0/schema"
} The utilities in this package will load the schema from the URL and use it for
validating the document. Obviously, this has a hit on performance and depends on
the availability of the server and an internet connection. Hence you are
encouraged to ship the schema with your package. Use the $uriRetriever = new UriRetriever();
$uriRetriever->setUriRetriever(new LocalUriRetriever(
// base directory
__DIR__.'/../res/schemas',
// list of schema mappings
array(
'http://example.org/schemas/1.0/schema' => 'schema-1.0.json',
)
));
$validator = new JsonValidator(null, $uriRetriever);
$encoder = new JsonEncoder($validator);
$decoder = new JsonDecoder($validator);
// ... ConversionYou can implement use stdClass;
use Webmozart\Json\Conversion\JsonConverter;
class ConfigFileJsonConverter implements JsonConverter
{
const SCHEMA = 'http://example.org/schemas/1.0/schema';
public function toJson($configFile, array $options = array())
{
$jsonData = new stdClass();
$jsonData->{'$schema'} = self::SCHEMA;
if (null !== $configFile->getApplicationName()) {
$jsonData->application = $configFile->getApplicationName();
}
// ...
return $jsonData;
}
public function fromJson($jsonData, array $options = array())
{
$configFile = new ConfigFile();
if (isset($jsonData->application)) {
$configFile->setApplicationName($jsonData->application);
}
// ...
return $configFile;
}
} Loading and dumping $converter = new ConfigFileJsonConverter();
// Load config.json as ConfigFile object
$jsonData = $decoder->decodeFile('/path/to/config.json');
$configFile = $converter->fromJson($jsonData);
// Save ConfigFile object as config.json
$jsonData = $converter->toJson($configFile);
$encoder->encodeFile($jsonData, '/path/to/config.json'); You can automate the schema validation of your use Webmozart\Json\Validation\ValidatingConverter;
$converter = new ValidatingConverter(new ConfigFileJsonConverter()); You can also validate against an explicit schema by passing the schema to the
use Webmozart\Json\Validation\ValidatingConverter;
$converter = new ValidatingConverter(
new ConfigFileJsonConverter(),
__DIR__.'/../res/schema/config-schema.json'
); Versioning and MigrationWhen you continuously develop an application, you will enter the situation that you need to change your JSON schemas. Updating JSON files to match their changed schemas can be challenging and time consuming. This package supports a versioning mechanism to automate this migration. Imagine config.json (version 1.0) {
"$schema": "http://example.org/schemas/1.0/schema",
"application": "Hello world!"
} config.json (version 2.0) {
"$schema": "http://example.org/schemas/2.0/schema",
"application.name": "Hello world!"
} config.json (version 3.0) {
"$schema": "http://example.org/schemas/3.0/schema",
"application": {
"name": "Hello world!"
}
} You can support files in any of these versions by implementing:
Let's look at an example of a use stdClass;
use Webmozart\Json\Conversion\JsonConverter;
class ConfigFileJsonConverter implements JsonConverter
{
const SCHEMA = 'http://example.org/schemas/3.0/schema';
public function toJson($configFile, array $options = array())
{
$jsonData = new stdClass();
$jsonData->{'$schema'} = self::SCHEMA;
if (null !== $configFile->getApplicationName()) {
$jsonData->application = new stdClass();
$jsonData->application->name = $configFile->getApplicationName();
}
// ...
return $jsonData;
}
public function fromJson($jsonData, array $options = array())
{
$configFile = new ConfigFile();
if (isset($jsonData->application->name)) {
$configFile->setApplicationName($jsonData->application->name);
}
// ...
return $configFile;
}
} This converter can be used as described in the previous section. However,
it can only be used with We can add support for older files by implementing the
use Webmozart\Json\Migration\JsonMigration;
class ConfigFileJson20To30Migration implements JsonMigration
{
const SOURCE_SCHEMA = 'http://example.org/schemas/2.0/schema';
const TARGET_SCHEMA = 'http://example.org/schemas/3.0/schema';
public function getSourceVersion()
{
return '2.0';
}
public function getTargetVersion()
{
return '3.0';
}
public function up(stdClass $jsonData)
{
$jsonData->{'$schema'} = self::TARGET_SCHEMA;
if (isset($jsonData->{'application.name'})) {
$jsonData->application = new stdClass();
$jsonData->application->name = $jsonData->{'application.name'};
unset($jsonData->{'application.name'});
)
}
public function down(stdClass $jsonData)
{
$jsonData->{'$schema'} = self::SOURCE_SCHEMA;
if (isset($jsonData->application->name)) {
$jsonData->{'application.name'} = $jsonData->application->name;
unset($jsonData->application);
)
}
} With a list of such migrations, we can create a use Webmozart\Json\Migration\MigratingConverter;
use Webmozart\Json\Migration\MigrationManager;
// Written for version 3.0
$converter = new ConfigFileJsonConverter();
// Support for older versions. The order of migrations does not matter.
$migrationManager = new MigrationManager(array(
new ConfigFileJson10To20Migration(),
new ConfigFileJson20To30Migration(),
));
// Decorate the converter
$converter = new MigratingConverter($converter, $migrationManager); The resulting converter is able to load and dump JSON files in any of the versions 1.0, 2.0 and 3.0. // Loads a file in version 1.0, 2.0 or 3.0
$jsonData = $decoder->decodeFile('/path/to/config.json');
$configFile = $converter->fromJson($jsonData);
// Writes the file in the latest version by default (3.0)
$jsonData = $converter->toJson($configFile);
$encoder->encodeFile($jsonData, '/path/to/config.json');
// Writes the file in a specific version
$jsonData = $converter->toJson($configFile, array(
'targetVersion' => '2.0',
));
$encoder->encodeFile($jsonData, '/path/to/config.json'); Validation of Different VersionsIf you want to add schema validation, wrap your encoder into a
// Written for version 3.0
$converter = new ConfigFileJsonConverter();
// Decorate to validate against the schema at version 3.0
$converter = new ValidatingConverter($converter);
// Decorate to support different versions
$converter = new MigratingConverter($converter, $migrationManager);
// Decorate to validate against the old schema
$converter = new ValidatingConverter($converter); If you store the version in a // Written for version 3.0
$converter = new ConfigFileJsonConverter();
// Decorate to validate against the schema at version 3.0
$converter = new ValidatingConverter($converter, __DIR__.'/../res/schema/config-schema-3.0.json');
// Decorate to support different versions
$converter = new MigratingConverter($converter, $migrationManager);
// Decorate to validate against the old schema
$converter = new ValidatingConverter($converter, function ($jsonData) {
return __DIR__.'/../res/schema/config-schema-'.$jsonData->version.'.json'
}); Using Custom Schema VersioningBy default, the version of the schema is stored in the schema name: {
"$schema": "http://example.com/schemas/1.0/my-schema"
} The version must be enclosed by slashes. Appending the version to the schema, for example, won't work: {
"$schema": "http://example.com/schemas/my-schema-1.0"
} You can however customize the format of the schema URI by creating a
use Webmozart\Json\Versioning\SchemaUriVersioner;
$versioner = new SchemaUriVersioner('~(?<=-)\d+\.\d+(?=$)~');
$migrationManager = new MigrationManager(array(
// migrations...
), $versioner);
// ... The regular expression must match the version only. Make sure to wrap
characters before and after the version in look-around assertions ( Storing the Version in a FieldInstead of storing the version in the schema URI, you could also store it in a separate field. For example, the field "version": {
"version": "1.0"
} This use case is supported by the use Webmozart\Json\Versioning\VersionFieldVersioner;
$versioner = new VersionFieldVersioner();
$migrationManager = new MigrationManager(array(
// migrations...
), $versioner);
// ... The constructor of AuthorsContributeContributions to the package are always welcome!
SupportIf you are having problems, send a mail to [email protected] or shout out to @webmozart on Twitter. LicenseAll contents of this package are licensed under the MIT license. |
2023-10-27
2022-08-15
2022-08-17
2022-09-23
2022-08-13
请发表评论