File: basic_csv_reader.md

package info (click to toggle)
jsoncons 1.3.2-1
  • links: PTS, VCS
  • area: main
  • in suites: forky, sid, trixie
  • size: 17,584 kB
  • sloc: cpp: 136,382; sh: 33; makefile: 5
file content (444 lines) | stat: -rw-r--r-- 12,663 bytes parent folder | download
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
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
### jsoncons::csv::basic_csv_reader

```cpp
#include <jsoncons_ext/csv/csv_reader.hpp>

template<
    typename CharT,
    typename Source=jsoncons::stream_source<CharT>,
    typename TempAllocator=std::allocator<char>>
class basic_csv_reader 
```

The `basic_csv_reader` class reads a [CSV file](http://tools.ietf.org/html/rfc4180) and produces JSON parse events.

`basic_csv_reader` is noncopyable and nonmoveable.

A number of specializations for common character types are defined:

Type                  |Definition
----------------------|------------------------------
`csv_string_reader`   |`basic_csv_string_reader<char,string_source<char>>`         (since 0.164.0)
`wcsv_stringreader`   |`basic_csv_string_reader<wchar_t,string_source<wchar_t>>`   (since 0.164.0)
`csv_stream_reader`   |`basic_csv_stream_reader<char,stream_source<char>>`         (since 0.164.0)
`wcsv_stream_reader`  |`basic_csv_stream_reader<wchar_t,stream_source<wchar_t>>`   (since 0.164.0)
`csv_reader`          |Constructible from either a string or stream                (deprecated since 0.164.0)
`wcsv_reader`         |Constructible from either a wide character string or stream (deprecated since 0.164.0)

#### Member types

Type                       |Definition
---------------------------|------------------------------
char_type                  |CharT
source_type                |Source

#### Constructors

    template <typename Sourceable>
    basic_csv_reader(Sourceable&& source,
                     basic_json_visitor<CharT>& visitor, 
                     const TempAllocator& alloc = TempAllocator()); (1)


    template <typename Sourceable>
    basic_csv_reader(Sourceable&& source,
                     basic_json_visitor<CharT>& visitor,
                     const basic_csv_options<CharT>& options, 
                     const TempAllocator& alloc = TempAllocator()); (2)

    template <typename Sourceable>
    basic_csv_reader(Sourceable&& source,
                     basic_json_visitor<CharT>& visitor,
                     std::function<bool(csv_errc,const ser_context&)> err_handler, 
                     const TempAllocator& alloc = TempAllocator()); (3)

    template <typename Sourceable>
    basic_csv_reader(Sourceable&& source,
                     basic_json_visitor<CharT>& visitor,
                     const basic_csv_options<CharT>& options,
                     std::function<bool(csv_errc,const ser_context&)> err_handler, 
                     const TempAllocator& alloc = TempAllocator()); (4)

(1) Constructs a `basic_csv_reader` that reads from a character sequence or stream `source`
and a [basic_json_visitor](../basic_json_visitor.md) that receives
JSON events. Uses default [basic_csv_options](basic_csv_options.md).

(2) Constructs a `basic_csv_reader` that  that reads from a character sequence or stream `source`, a [basic_json_visitor](../basic_json_visitor.md) that receives
JSON events, and [basic_csv_options](basic_csv_options.md).

(3) Constructs a `basic_csv_reader` that reads from a character sequence or stream `source`, a [basic_json_visitor](../basic_json_visitor.md) that receives
JSON events and the specified [JSON parsing error handling](../err_handler.md).
Uses default [basic_csv_options](basic_csv_options.md).

(4) Constructs a `basic_csv_reader` that reads from a character sequence or stream `source`, a [basic_json_visitor](../basic_json_visitor.md) that receives
JSON events, [basic_csv_options](basic_csv_options.md),
and the specified [JSON parsing error handling](../err_handler.md).

Note: It is the programmer's responsibility to ensure that `basic_csv_reader` does not outlive any source or 
visitor passed in the constuctor, as `basic_csv_reader` holds pointers to but does not own these resources.

#### Parameters

`source` - a value from which a `jsoncons::basic_string_view<char_type>` is constructible, 
or a value from which a `source_type` is constructible. In the case that a `jsoncons::basic_string_view<char_type>` is constructible
from `source`, `source` is dispatched immediately to the parser. Otherwise, the `basic_csv_reader` reads from a `source_type` in chunks. 

#### Member functions

    bool eof() const
Returns `true` when there is no more data to be read from the stream, `false` otherwise

    void read()
Reports JSON related events for JSON objects, arrays, object members and array elements to a [basic_json_visitor](../basic_json_visitor.md), such as a [json_decoder](json_decoder.md).
Throws a [ser_error](../ser_error.md) if parsing fails.

### Examples

#### Reading a comma delimted file into an array of json values

#### Comma delimited input file 
```
country_code,name
ABW,ARUBA
ATF,"FRENCH SOUTHERN TERRITORIES, D.R. OF"
VUT,VANUATU
WLF,WALLIS & FUTUNA ISLANDS
```
Note 

- The first record contains a header line, but we're going to ignore that and read the entire file as an array of arrays.
- The third record has a field value that contains an embedded comma, so it must be quoted.

#### Code
```cpp
std::string in_file = "countries.csv";
std::ifstream is(in_file);

json_decoder<json> decoder;

csv_stream_reader reader(is,decoder);
reader.read();
json countries = decoder.get_result();

std::cout << pretty_print(countries) << '\n';
```
#### Output 
```json
[
    ["country_code","name"],
    ["ABW","ARUBA"],
    ["ATF","FRENCH SOUTHERN TERRITORIES, D.R. OF"],
    ["VUT","VANUATU"],
    ["WLF","WALLIS & FUTUNA ISLANDS"]
]
```
#### Reading a tab delimted file into an array of json objects

#### Tab delimited input file
```
employee-no employee-name   dept    salary  note
00000001    Smith, Matthew  sales   150,000.00      
00000002    Brown, Sarah    sales   89,000.00       
00000003    Oberc, Scott    finance 110,000.00      
00000004    Scott, Colette  sales   75,000.00       """Exemplary"" employee
Dependable, trustworthy"
```
Note 

- The first record is a header line, which will be used to associate data values with names
- The fifth record has a field value that contains embedded quotes and a new line character, so it must be quoted and the embedded quotes escaped.

#### Code
```cpp
std::string in_file = "employees.txt";
std::ifstream is(in_file);

json_decoder<json> decoder;
auto options = csv_options{}          
    .field_delimiter = '\t'
    .assume_header = true;

csv_stream_reader reader(is,decoder,options);
reader.read();
json employees = decoder.get_result();

std::cout << pretty_print(employees) << '\n';
```

#### Output

```json
[
    {
        "dept":"sales",
        "employee-name":"Smith, Matthew",
        "employee-no":"00000001",
        "note":"",
        "salary":"150,000.00"
    },
    {
        "dept":"sales",
        "employee-name":"Brown, Sarah",
        "employee-no":"00000002",
        "note":"",
        "salary":"89,000.00"
    },
    {
        "dept":"finance",
        "employee-name":"Oberc, Scott",
        "employee-no":"00000003",
        "note":"",
        "salary":"110,000.00"
    },
    {
        "dept":"sales",
        "employee-name":"Scott, Colette",
        "employee-no":"00000004",
        "note":"\"Exemplary\" employee\nDependable, trustworthy",
        "salary":"75,000.00"
    }
]
```

#### Reading the comma delimited file as an array of objects with user supplied columns names

Note 

- The first record contains a header line, but we're going to ignore that and use our own names for the fields.

#### Code
```cpp
std::string in_file = "countries.csv";
std::ifstream is(in_file);

json_decoder<json> decoder;

auto options = csv_options{}          
    .column_names("Country Code,Name")
    .header_lines(1);

csv_stream_reader reader(is,decoder,options);
reader.read();
json countries = decoder.get_result();

std::cout << pretty_print(countries) << '\n';
```

#### Output 
```json
[
    {
        "Country Code":"ABW",
        "Name":"ARUBA"
    },
    {
        "Country Code":"ATF",
        "Name":"FRENCH SOUTHERN TERRITORIES, D.R. OF"
    },
    {
        "Country Code":"VUT",
        "Name":"VANUATU"
    },
    {
        "Country Code":"WLF",
        "Name":"WALLIS & FUTUNA ISLANDS"
    }
]
```


#### Reading a comma delimited file with different mapping strategies

#### Input

```csv
Date,1Y,2Y,3Y,5Y
2017-01-09,0.0062,0.0075,0.0083,0.011
2017-01-08,0.0063,0.0076,0.0084,0.0112
2017-01-08,0.0063,0.0076,0.0084,0.0112
```

#### Code

```cpp
json_decoder<ojson> decoder;
auto options = csv_options{}          
    .assume_header(true)
    .column_types("string,float,float,float,float")
    .mapping_kind(csv_mapping_kind::n_rows);

std::istringstream is1("bond_yields.csv");
csv_stream_reader reader1(is1,decoder,options);
reader1.read();
ojson val1 = decoder.get_result();
std::cout << "\n(1)\n"<< pretty_print(val1) << "\n";

options.mapping_kind(csv_mapping_kind::n_objects);
std::istringstream is2("bond_yields.csv");
csv_stream_reader reader2(is2,decoder,options);
reader2.read();
ojson val2 = decoder.get_result();
std::cout << "\n(2)\n"<< pretty_print(val2) << "\n";

options.mapping_kind(csv_mapping_kind::m_columns);
std::istringstream is3("bond_yields.csv");
csv_stream_reader reader3(is3, decoder, options);
reader3.read();
ojson val3 = decoder.get_result();
std::cout << "\n(3)\n" << pretty_print(val3) << "\n";
```

#### Output

```json
(1)
[
    ["Date","1Y","2Y","3Y","5Y"],
    ["2017-01-09",0.0062,0.0075,0.0083,0.011],
    ["2017-01-08",0.0063,0.0076,0.0084,0.0112],
    ["2017-01-08",0.0063,0.0076,0.0084,0.0112]
]

(2)
[
    {
        "Date": "2017-01-09",
        "1Y": 0.0062,
        "2Y": 0.0075,
        "3Y": 0.0083,
        "5Y": 0.011
    },
    {
        "Date": "2017-01-08",
        "1Y": 0.0063,
        "2Y": 0.0076,
        "3Y": 0.0084,
        "5Y": 0.0112
    },
    {
        "Date": "2017-01-08",
        "1Y": 0.0063,
        "2Y": 0.0076,
        "3Y": 0.0084,
        "5Y": 0.0112
    }
]

(3)
{
    "Date": ["2017-01-09","2017-01-08","2017-01-08"],
    "1Y": [0.0062,0.0063,0.0063],
    "2Y": [0.0075,0.0076,0.0076],
    "3Y": [0.0083,0.0084,0.0084],
    "5Y": [0.011,0.0112,0.0112]
}
```

#### Convert CSV to json when last column repeats

```cpp
int main()
{
    const std::string bond_yields = R"(Date,Yield
2017-01-09,0.0062,0.0075,0.0083,0.011,0.012
2017-01-08,0.0063,0.0076,0.0084,0.0112,0.013
2017-01-08,0.0063,0.0076,0.0084,0.0112,0.014
)";

    // array of arrays
    json_decoder<ojson> decoder1;
    auto options1 = csv_options{}
        .header_lines(1)
        .assume_header(false)
        .column_types("string,float*");
    std::istringstream is1(bond_yields);
    csv_stream_reader reader1(is1, decoder1, options1);
    reader1.read();
    ojson val1 = decoder1.get_result();
    std::cout << "\n(1)\n" << pretty_print(val1) << "\n";

    // array of objects
    json_decoder<ojson> decoder2;
    auto options2 = csv_options{}
        .assume_header(true)
        .column_types("string,[float*]");
    std::istringstream is2(bond_yields);
    csv_stream_reader reader2(is2, decoder2, options2);
    reader2.read();
    ojson val2 = decoder2.get_result();
    std::cout << "\n(2)\n" << pretty_print(val2) << "\n";
}
```

Output:
```
(1)
[
    ["2017-01-09",0.0062,0.0075,0.0083,0.011,0.012],
    ["2017-01-08",0.0063,0.0076,0.0084,0.0112,0.013],
    ["2017-01-08",0.0063,0.0076,0.0084,0.0112,0.014]
]

(2)
[
    {
        "Date": "2017-01-09",
        "Yield": [0.0062,0.0075,0.0083,0.011,0.012]
    },
    {
        "Date": "2017-01-08",
        "Yield": [0.0063,0.0076,0.0084,0.0112,0.013]
    },
    {
        "Date": "2017-01-08",
        "Yield": [0.0063,0.0076,0.0084,0.0112,0.014]
    }
]
```

#### Convert CSV to json when last two columns repeat

```cpp
const std::string holidays = R"(1,CAD,2,UK,3,EUR,4,US + UK,5,US
38719,2-Jan-2006,40179,1-Jan-2010,38719,2-Jan-2006,38719,2-Jan-2006,39448,1-Jan-2008
38733,16-Jan-2006,40270,2-Apr-2010,38733,16-Jan-2006,38733,16-Jan-2006,39468,21-Jan-2008
)";

    json_decoder<ojson> decoder;
    auto options = csv_options{}          
        .column_types("[integer,string]*");

    // Default
    std::istringstream is1(holidays);
    csv_stream_reader reader1(is1, decoder, options);
    reader1.read();
    ojson val1 = decoder.get_result();
    std::cout << pretty_print(val1) << "\n";
```

Output:
```
[
    [
        [1,"CAD"],
        [2,"UK"],
        [3,"EUR"],
        [4,"US + UK"],
        [5,"US"]
    ],
    [
        [38719,"2-Jan-2006"],
        [40179,"1-Jan-2010"],
        [38719,"2-Jan-2006"],
        [38719,"2-Jan-2006"],
        [39448,"1-Jan-2008"]
    ],
    [
        [38733,"16-Jan-2006"],
        [40270,"2-Apr-2010"],
        [38733,"16-Jan-2006"],
        [38733,"16-Jan-2006"],
        [39468,"21-Jan-2008"]
    ]
]
```