Skip to content

Commit f824f80

Browse files
gakadasindresorhus
authored andcommitted
Add beforeParse and reviver options (#14)
1 parent 633ec57 commit f824f80

File tree

3 files changed

+39
-6
lines changed

3 files changed

+39
-6
lines changed

index.js

Lines changed: 10 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -5,7 +5,14 @@ const stripBom = require('strip-bom');
55
const parseJson = require('parse-json');
66
const pify = require('pify');
77

8-
const parse = (data, fp) => parseJson(stripBom(data), path.relative('.', fp));
8+
const parse = (data, fp, options) => {
9+
options = options || {};
10+
data = stripBom(data);
11+
if (typeof options.beforeParse === 'function') {
12+
data = options.beforeParse(data);
13+
}
14+
return parseJson(data, options.reviver, path.relative('.', fp));
15+
};
916

10-
module.exports = fp => pify(fs.readFile)(fp, 'utf8').then(data => parse(data, fp));
11-
module.exports.sync = fp => parse(fs.readFileSync(fp, 'utf8'), fp);
17+
module.exports = (fp, options) => pify(fs.readFile)(fp, 'utf8').then(data => parse(data, fp, options));
18+
module.exports.sync = (fp, options) => parse(fs.readFileSync(fp, 'utf8'), fp, options);

readme.md

Lines changed: 18 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -26,14 +26,30 @@ loadJsonFile('foo.json').then(json => {
2626

2727
## API
2828

29-
### loadJsonFile(filepath)
29+
### loadJsonFile(filepath, [options])
3030

3131
Returns a promise for the parsed JSON.
3232

33-
### loadJsonFile.sync(filepath)
33+
### loadJsonFile.sync(filepath, [options])
3434

3535
Returns the parsed JSON.
3636

37+
#### options
38+
39+
Type: `Object`
40+
41+
##### beforeParse
42+
43+
Type: `Function`
44+
45+
Applies a function to the JSON string before parsing.
46+
47+
##### reviver
48+
49+
Type: `Function`
50+
51+
Prescribes how the value originally produced by parsing is transformed, before being returned. See [`JSON.parse` docs](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/JSON/parse#Using_the_reviver_parameter) for more.
52+
3753

3854
## Related
3955

test.js

Lines changed: 11 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,6 @@
11
import path from 'path';
22
import test from 'ava';
3-
import m from './';
3+
import m from '.';
44

55
const fixture = path.join(__dirname, 'package.json');
66

@@ -12,3 +12,13 @@ test('async', async t => {
1212
test('sync', t => {
1313
t.is(m.sync(fixture).name, 'load-json-file');
1414
});
15+
16+
test('beforeParse', async t => {
17+
const data = await m(fixture, {beforeParse: s => s.replace('"name": "load-json-file"', '"name": "foo"')});
18+
t.is(data.name, 'foo');
19+
});
20+
21+
test('reviver', async t => {
22+
const data = await m(fixture, {reviver: (k, v) => k === 'name' ? 'foo' : v});
23+
t.is(data.name, 'foo');
24+
});

0 commit comments

Comments
 (0)