Validate JSON

An example package.json for a Python package

json <- '{
  "name": "dunderscore",
  "version": "1.2.3",
  "description": "The Pythonic JavaScript toolkit",
  "devDependencies": {
    "pest": "^23.4.1"
  },
  "main": "index.js",
  "scripts": {
    "test": "pest"
  },
  "license": "MIT"
}'

Define a schema

check_json <- Schema$new("CheckJSON",
  name = fields$character(required=TRUE),
  version = fields$character(required=TRUE),
  description = fields$character(required=TRUE),
  main = fields$character(),
  homepage = fields$url(),
  scripts = fields$named_list(keys=fields$character(), values=fields$character()),
  license = fields$character(required=TRUE),
  dependencies = fields$named_list(keys=fields$character(), values=fields$character()),
  dev_dependencies = fields$named_list(
    keys=fields$character(),
    values=fields$character(),
    data_key="devDependencies",
  ),
  unknown = "include"
)

Check the json against the schema. In this case it’s valid, so we get the list output

check_json$load_json(json)
#> $name
#> [1] "dunderscore"
#> 
#> $version
#> [1] "1.2.3"
#> 
#> $description
#> [1] "The Pythonic JavaScript toolkit"
#> 
#> $main
#> [1] "index.js"
#> 
#> $scripts
#> $scripts$test
#> [1] "pest"
#> 
#> 
#> $license
#> [1] "MIT"
#> 
#> $dev_dependencies
#> $dev_dependencies$pest
#> [1] "^23.4.1"

In the above case, the JSON is valid. What if we give it bad JSON? Here, a required field (license) is missing:

json_bad <- '{
  "name": "dunderscore",
  "version": "1.2.3",
  "description": "The Pythonic JavaScript toolkit",
  "devDependencies": {
    "pest": "^23.4.1"
  },
  "main": "index.js",
  "scripts": {
    "test": "pest"
  }
}'

Check it

check_json$load_json(json_bad)
#> Error: ValidationError: Missing data for required field.