File: json.md

package info (click to toggle)
ruby-faraday 2.14.0-1
  • links: PTS, VCS
  • area: main
  • in suites: forky, sid
  • size: 2,008 kB
  • sloc: ruby: 6,509; sh: 10; makefile: 8
file content (81 lines) | stat: -rw-r--r-- 2,454 bytes parent folder | download | duplicates (2)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
# JSON Encoding/Decoding

## JSON Requests

The `JSON` request middleware converts a `Faraday::Request#body` hash of key/value pairs into a JSON request body.
The middleware also automatically sets the `Content-Type` header to `application/json`,
processes only requests with matching Content-Type or those without a type and
doesn't try to encode bodies that already are in string form.

### Example Usage

```ruby
conn = Faraday.new(...) do |f|
  f.request :json
  ...
end

conn.post('/', { a: 1, b: 2 })
# POST with
# Content-Type: application/json
# Body: {"a":1,"b":2}
```

### Using custom JSON encoders

By default, middleware utilizes Ruby's `json` to generate JSON strings.

Other encoders can be used by specifying `encoder` option for the middleware:
* a module/class which implements `dump`
* a module/class-method pair to be used 

```ruby
require 'oj'

Faraday.new(...) do |f|
  f.request :json, encoder: Oj
end

Faraday.new(...) do |f|
  f.request :json, encoder: [Oj, :dump]
end
```

## JSON Responses

The `JSON` response middleware parses response body into a hash of key/value pairs.
The behaviour can be customized with the following options:
* **parser_options:** options that will be sent to the JSON.parse method. Defaults to {}.
* **content_type:** Single value or Array of response content-types that should be processed. Can be either strings or Regex. Defaults to `/\bjson$/`.
* **preserve_raw:** If set to true, the original un-parsed response will be stored in the `response.env[:raw_body]` property. Defaults to `false`.

### Example Usage

```ruby
conn = Faraday.new('http://httpbingo.org') do |f|
  f.response :json, **options
end

conn.get('json').body
# => {"slideshow"=>{"author"=>"Yours Truly", "date"=>"date of publication", "slides"=>[{"title"=>"Wake up to WonderWidgets!", "type"=>"all"}, {"items"=>["Why <em>WonderWidgets</em> are great", "Who <em>buys</em> WonderWidgets"], "title"=>"Overview", "type"=>"all"}], "title"=>"Sample Slide Show"}}
```

### Using custom JSON decoders

By default, middleware utilizes Ruby's `json` to parse JSON strings.

Other decoders can be used by specifying `decoder` parser option for the middleware:
* a module/class which implements `load`
* a module/class-method pair to be used 

```ruby
require 'oj'

Faraday.new(...) do |f|
  f.response :json, parser_options: { decoder: Oj }
end

Faraday.new(...) do |f|
  f.response :json, parser_options: { decoder: [Oj, :load] }
end
```