You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
Copy file name to clipboardExpand all lines: readme.md
+14Lines changed: 14 additions & 0 deletions
Display the source diff
Display the rich diff
Original file line number
Diff line number
Diff line change
@@ -734,9 +734,12 @@ Default: `JSON.parse()`
734
734
735
735
User-defined JSON-parsing function.
736
736
737
+
The function receives the response text as the first argument and a context object as the second argument containing the `request` ([`Request`](https://developer.mozilla.org/en-US/docs/Web/API/Request)) and `response` ([`Response`](https://developer.mozilla.org/en-US/docs/Web/API/Response)).
738
+
737
739
Use-cases:
738
740
1. Parse JSON via the [`bourne` package](https://github.com/hapijs/bourne) to protect from prototype pollution.
739
741
2. Parse JSON with [`reviver` option of `JSON.parse()`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/JSON/parse).
742
+
3. Log or handle JSON parse errors with request context.
Copy file name to clipboardExpand all lines: source/types/options.ts
+17-1Lines changed: 17 additions & 1 deletion
Original file line number
Diff line number
Diff line change
@@ -41,9 +41,12 @@ export type KyOptions = {
41
41
/**
42
42
User-defined JSON-parsing function.
43
43
44
+
The function receives the response text as the first argument and a context object as the second argument containing the `request` and `response`.
45
+
44
46
Use-cases:
45
47
1. Parse JSON via the [`bourne` package](https://github.com/hapijs/bourne) to protect from prototype pollution.
46
48
2. Parse JSON with [`reviver` option of `JSON.parse()`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/JSON/parse).
49
+
3. Log or handle JSON parse errors with request context.
47
50
48
51
@default JSON.parse()
49
52
@@ -56,8 +59,21 @@ export type KyOptions = {
56
59
parseJson: text => bourne(text)
57
60
}).json();
58
61
```
62
+
63
+
@example
64
+
```
65
+
import ky from 'ky';
66
+
67
+
const json = await ky('https://example.com', {
68
+
parseJson: (text, {request, response}) => {
69
+
console.log(`Parsing JSON from ${request.url} (status: ${response.status})`);
70
+
return JSON.parse(text);
71
+
}
72
+
}).json();
73
+
```
59
74
*/
60
-
parseJson?: (text: string)=>unknown;
75
+
// `options` is intentionally not included in the context to avoid exposing Ky internals through a parsing callback. `request`/`response` already provide the metadata needed for logging.
0 commit comments