Skip to content

Commit 2a97634

Browse files
feat: support reviver on JSON.parse (#5926)
* test: test to support reviver on JSON.parse * feat: support reviver for JSON.parse on parse response data #5924 --------- Co-authored-by: Jay <[email protected]>
1 parent 7960d34 commit 2a97634

File tree

3 files changed

+20
-1
lines changed

3 files changed

+20
-1
lines changed

index.d.ts

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -361,6 +361,7 @@ export interface AxiosRequestConfig<D = any> {
361361
lookup?: ((hostname: string, options: object, cb: (err: Error | null, address: LookupAddress | LookupAddress[], family?: AddressFamily) => void) => void) |
362362
((hostname: string, options: object) => Promise<[address: LookupAddressEntry | LookupAddressEntry[], family?: AddressFamily] | LookupAddress>);
363363
withXSRFToken?: boolean | ((config: InternalAxiosRequestConfig) => boolean | undefined);
364+
parseReviver?: (this: any, key: string, value: any) => any;
364365
fetchOptions?: Omit<RequestInit, 'body' | 'headers' | 'method' | 'signal'> | Record<string, any>;
365366
}
366367

lib/defaults/index.js

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -111,7 +111,7 @@ const defaults = {
111111
const strictJSONParsing = !silentJSONParsing && JSONRequested;
112112

113113
try {
114-
return JSON.parse(data);
114+
return JSON.parse(data, this.parseReviver);
115115
} catch (e) {
116116
if (strictJSONParsing) {
117117
if (e.name === 'SyntaxError') {

test/unit/adapters/http.js

Lines changed: 18 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -2332,4 +2332,22 @@ describe('supports http with nodejs', function () {
23322332
}, /ENOTFOUND/);
23332333
});
23342334
});
2335+
2336+
describe('JSON', function() {
2337+
it('should support reviver on JSON.parse', async function () {
2338+
server = await startHTTPServer(async (_, res) => {
2339+
res.end(JSON.stringify({
2340+
foo: 'bar'
2341+
}));
2342+
});
2343+
2344+
const {data} = await axios.get(LOCAL_SERVER_URL, {
2345+
parseReviver: (key, value) => {
2346+
return key === 'foo' ? 'success' : value;
2347+
},
2348+
});
2349+
2350+
assert.deepStrictEqual(data, {foo: 'success'});
2351+
});
2352+
});
23352353
});

0 commit comments

Comments
 (0)