Description
A library to make changes to objects imported from JSON files reflected in the file
Installation
npm i @nano-utils/json-import
or
yarn add @nano-utils/json-import
Usage
import { importJSON } from '@nano-utils/json-import';
/** data.json
* {
* "foo": "bar"
* }
*/
const obj = importJSON('./data.json');
console.log(obj); // { foo: 'bar' }
This package comes fully typed:
import { importJSON } from '@nano-utils/json-import';
type MyObject = {
foo: string;
};
/** data.json
* {
* "foo": "bar"
* }
*/
const obj: MyObject = importJSON<MyObject>('./data.json');
console.log(obj); // { foo: 'bar' }
We support using the yup
library to perform validation:
import { importJSON } from '@nano-utils/json-import';
import { object, string } from 'yup';
type MyObject = {
foo: string;
};
const schema = object({
foo: string()
});
/** data.json
* {
* "foo": "bar"
* }
*/
const obj: MyObject = importJSON<MyObject>('./data.json', schema);
console.log(obj); // { foo: 'bar' }
Usage Notes:
- When working with arrays, make sure to always assign values, do not use methods such as
push
orsplice
. Otherwise, the underlying proxy will not detect your changes. - When validating with
yup
, it is recommended to use strict mode for your types, otherwise you may run into type coercion issues (see here for more information.) -
requireJSON
is equivalent toimportJSON