packagejsonschema

Load a package.json file as a PackageJson struct.

example workflow

Why?

You want to load a package.json file and interact with it as a struct.

Installation

Add this line to the dependencies section of your Cargo.toml:

toml package_json_schema = "0.1.0"

If you would like to include validation then add the validate feature. This will validate all the fields the loaded json. Emails, the package name, the version.

toml package_json_schema = { version = "0.1.0", features = ["validate"] }

Usage

The following example shows how to load a package.json file and use it as a struct.

```rust use packagejsonschema::PackageJson;

let contents = r###" { "name": "my-package", "version": "0.1.0", "dependencies": { "@sveltejs/kit": "1.0.0-next.396" }, "peerDependencies": { "aws-sdk": "2.1185.0" } } "###;

let packagejson = PackageJson::tryfrom(contents).unwrap(); asserteq!(packagejson.name.unwrap(), "my-package"); asserteq!(packagejson.version.unwrap(), "0.1.0"); ```

This crate leaves it to the user to load the package.json content from the filesystem. Here is an example of loading the file contents and parsing the contents into a struct.

```rust use std::fs::readtostring; use packagejsonschema::PackageJson;

let contents = readtostring("./tests/fixtures/1/package.json").unwrap(); let packagejson = PackageJson::tryfrom(contents).unwrap();

asserteq!(packagejson.name.unwrap(), "test"); ```

A package.json file can also be created from a builder.

```rust use packagejsonschema::PackageJson; use packagejsonschema::AdditionalFields; use packagejsonschema::Person; use indexmap::IndexMap;

let mut additionalfields: AdditionalFields = IndexMap::new(); additionalfields.insert("custom".into(), "value".into());

let packagejson = PackageJson::builder() .name("awesome") .author(Person::String("Tester".into())) .other(additionalfields) .build(); let stringvalue = packagejson.trytostring().unwrap();

asserteq!( stringvalue, r#"{"name":"awesome","author":"Tester","custom":"value"}"# ); ```

To validate the package.json fields, enable the validate feature.

toml package_json_schema = { version = "0.1.0", features = ["validate"] }

And then use the validate method.

```rust use std::fs::readtostring; use packagejsonschema::PackageJson;

[cfg(feature = "validate")]

use validator::Validate;

let contents = readtostring("./tests/fixtures/1/package.json").unwrap(); let packagejson = PackageJson::tryfrom(contents).unwrap();

[cfg(feature = "validate")]

package_json.validate().unwrap(); ```

License

This project is licensed under the Unlicense license.