Skip to main content

estat_api/
response.rs

1//! Responses of `getStatsList`, `getMetaInfo`, `getStatsData` and `getStatsDatas`.
2//!
3//! Field names follow the e-Stat tags in snake case (`TABLE_INF` is
4//! `table_inf`, `@parentCode` is `parent_code`). Elements that e-Stat sends
5//! as an object when there is one and as an array when there are more are
6//! always a `Vec` here.
7//!
8//! Every struct keeps fields this crate does not know in `extra`, and
9//! serializing it gives them back.
10
11use crate::Dimension;
12use crate::de;
13use serde::de::Error as _;
14use serde::{Deserialize, Deserializer, Serialize, Serializer};
15use serde_json::{Map, Value};
16
17/// `RESULT` element: outcome of the request.
18#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
19#[serde(rename_all = "SCREAMING_SNAKE_CASE")]
20#[non_exhaustive]
21pub struct ApiResult {
22    /// `0` success, `1` success without data, `2` partly without data
23    /// (bulk requests only). `100` and above are errors and never reach a
24    /// response struct: they become [`EstatError::Api`](crate::EstatError::Api).
25    #[serde(deserialize_with = "de::number")]
26    pub status: u16,
27    /// Message for the status, such as `正常に終了しました。`.
28    #[serde(default, deserialize_with = "de::text")]
29    pub error_msg: String,
30    /// When the response was made, such as `2026-10-03T09:08:42.778+09:00`.
31    #[serde(default, deserialize_with = "de::text")]
32    pub date: String,
33    /// Fields this crate does not know yet, kept as received.
34    #[serde(flatten)]
35    pub extra: Map<String, Value>,
36}
37
38/// `RESULT_INF` element: position of the returned rows.
39///
40/// When more rows exist than `limit`, [`next_key`](Self::next_key) is the
41/// `startPosition` of the next request.
42#[derive(Debug, Clone, Default, PartialEq, Serialize, Deserialize)]
43#[serde(rename_all = "SCREAMING_SNAKE_CASE")]
44#[non_exhaustive]
45pub struct ResultInf {
46    /// Number of rows matching the conditions (`getStatsData` only).
47    #[serde(
48        default,
49        deserialize_with = "de::opt_number",
50        skip_serializing_if = "Option::is_none"
51    )]
52    pub total_number: Option<u64>,
53    /// First returned row, from 1.
54    #[serde(
55        default,
56        deserialize_with = "de::opt_number",
57        skip_serializing_if = "Option::is_none"
58    )]
59    pub from_number: Option<u64>,
60    /// Last returned row.
61    #[serde(
62        default,
63        deserialize_with = "de::opt_number",
64        skip_serializing_if = "Option::is_none"
65    )]
66    pub to_number: Option<u64>,
67    /// First row of the next page, `None` on the last page.
68    #[serde(
69        default,
70        deserialize_with = "de::opt_number",
71        skip_serializing_if = "Option::is_none"
72    )]
73    pub next_key: Option<u64>,
74    /// Fields this crate does not know yet, kept as received.
75    #[serde(flatten)]
76    pub extra: Map<String, Value>,
77}
78
79/// Name with a code attribute, such as `STAT_NAME` (`@code` is the
80/// government statistics code) or `GOV_ORG` (`@code` is the agency code).
81#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
82#[non_exhaustive]
83pub struct CodeName {
84    /// `@code`.
85    #[serde(rename = "@code", default)]
86    pub code: String,
87    /// Text of the element.
88    #[serde(rename = "$", default, deserialize_with = "de::text")]
89    pub name: String,
90    /// Fields this crate does not know yet, kept as received.
91    #[serde(flatten)]
92    pub extra: Map<String, Value>,
93}
94
95/// `TITLE` of a table. e-Stat sends a plain string when the table has no number.
96#[derive(Debug, Clone, PartialEq)]
97#[non_exhaustive]
98pub struct Title {
99    /// Table number (`@no`), such as `00100`.
100    pub no: Option<String>,
101    /// Title text.
102    pub name: String,
103}
104
105impl<'de> Deserialize<'de> for Title {
106    fn deserialize<D: Deserializer<'de>>(deserializer: D) -> Result<Self, D::Error> {
107        let value = Value::deserialize(deserializer)?;
108        let (no, name) = match &value {
109            Value::Object(map) => (map.get("@no"), map.get("$")),
110            _ => (None, Some(&value)),
111        };
112        let text = |v: Option<&Value>| match v {
113            None | Some(Value::Null) => Ok(String::new()),
114            Some(Value::String(s)) => Ok(s.clone()),
115            Some(Value::Number(n)) => Ok(n.to_string()),
116            Some(other) => Err(D::Error::custom(format!("expected a title, got {other}"))),
117        };
118        Ok(Title {
119            no: no.map(|v| text(Some(v))).transpose()?,
120            name: text(name)?,
121        })
122    }
123}
124
125impl Serialize for Title {
126    fn serialize<S: Serializer>(&self, serializer: S) -> Result<S::Ok, S::Error> {
127        match &self.no {
128            Some(no) => {
129                let mut map = Map::new();
130                map.insert("@no".into(), no.clone().into());
131                map.insert("$".into(), self.name.clone().into());
132                map.serialize(serializer)
133            }
134            None => serializer.serialize_str(&self.name),
135        }
136    }
137}
138
139/// `TABLE_INF` element: description of one statistical table.
140///
141/// The manual does not say which elements are always present, so all but
142/// the ID are optional.
143#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
144#[serde(rename_all = "SCREAMING_SNAKE_CASE")]
145#[non_exhaustive]
146pub struct TableInf {
147    /// Table ID (統計表ID, `@id`), such as `0003410379`. Pass it to
148    /// `meta_info` and `stats_data`.
149    #[serde(rename = "@id")]
150    pub id: String,
151    /// Request number (`@requestNo`), only in [`StatsDatas`] responses.
152    #[serde(
153        rename = "@requestNo",
154        default,
155        deserialize_with = "de::opt_number",
156        skip_serializing_if = "Option::is_none"
157    )]
158    pub request_no: Option<u32>,
159    /// Survey name (政府統計名) with the 8-digit government statistics code.
160    #[serde(
161        default,
162        deserialize_with = "de::object_or_empty",
163        skip_serializing_if = "Option::is_none"
164    )]
165    pub stat_name: Option<CodeName>,
166    /// Agency (作成機関名) with its 5-digit code.
167    #[serde(
168        default,
169        deserialize_with = "de::object_or_empty",
170        skip_serializing_if = "Option::is_none"
171    )]
172    pub gov_org: Option<CodeName>,
173    /// Name of the statistics and classification (提供統計名及び提供分類名).
174    #[serde(
175        default,
176        deserialize_with = "de::opt_text",
177        skip_serializing_if = "Option::is_none"
178    )]
179    pub statistics_name: Option<String>,
180    /// Title (表題).
181    #[serde(default, skip_serializing_if = "Option::is_none")]
182    pub title: Option<Title>,
183    /// Release cycle (提供周期), such as `年次` or `-`.
184    #[serde(
185        default,
186        deserialize_with = "de::opt_text",
187        skip_serializing_if = "Option::is_none"
188    )]
189    pub cycle: Option<String>,
190    /// Survey date (調査年月): `yyyymm`, `yyyymm-yyyymm`, or `0` when not set.
191    #[serde(
192        default,
193        deserialize_with = "de::opt_text",
194        skip_serializing_if = "Option::is_none"
195    )]
196    pub survey_date: Option<String>,
197    /// Release date (公開日), `yyyy-mm-dd`.
198    #[serde(
199        default,
200        deserialize_with = "de::opt_text",
201        skip_serializing_if = "Option::is_none"
202    )]
203    pub open_date: Option<String>,
204    /// Small area flag (小地域属性フラグ), `0` for ordinary tables.
205    #[serde(
206        default,
207        deserialize_with = "de::opt_number",
208        skip_serializing_if = "Option::is_none"
209    )]
210    pub small_area: Option<u8>,
211    /// Area level (集計地域区分), such as `全国` or `該当なし`.
212    #[serde(
213        default,
214        deserialize_with = "de::opt_text",
215        skip_serializing_if = "Option::is_none"
216    )]
217    pub collect_area: Option<String>,
218    /// Major statistics field (統計大分野) with its 2-digit code.
219    #[serde(
220        default,
221        deserialize_with = "de::object_or_empty",
222        skip_serializing_if = "Option::is_none"
223    )]
224    pub main_category: Option<CodeName>,
225    /// Minor statistics field (統計小分野) with its 2-digit code.
226    #[serde(
227        default,
228        deserialize_with = "de::object_or_empty",
229        skip_serializing_if = "Option::is_none"
230    )]
231    pub sub_category: Option<CodeName>,
232    /// Number of values in the table without filters.
233    #[serde(
234        default,
235        deserialize_with = "de::opt_number",
236        skip_serializing_if = "Option::is_none"
237    )]
238    pub overall_total_number: Option<u64>,
239    /// Date of the last update, `yyyy-mm-dd`.
240    #[serde(
241        default,
242        deserialize_with = "de::opt_text",
243        skip_serializing_if = "Option::is_none"
244    )]
245    pub updated_date: Option<String>,
246    /// `statistics_name` split into its parts.
247    #[serde(
248        default,
249        deserialize_with = "de::object_or_empty",
250        skip_serializing_if = "Option::is_none"
251    )]
252    pub statistics_name_spec: Option<StatisticsNameSpec>,
253    /// Explanations of the statistics. `None` when e-Stat sends an empty
254    /// element or explanations were not requested.
255    #[serde(
256        default,
257        deserialize_with = "de::object_or_empty",
258        skip_serializing_if = "Option::is_none"
259    )]
260    pub description: Option<Description>,
261    /// `title` split into its parts.
262    #[serde(
263        default,
264        deserialize_with = "de::object_or_empty",
265        skip_serializing_if = "Option::is_none"
266    )]
267    pub title_spec: Option<TitleSpec>,
268    /// Fields this crate does not know yet, kept as received.
269    #[serde(flatten)]
270    pub extra: Map<String, Value>,
271}
272
273/// `STATISTICS_NAME_SPEC` element.
274#[derive(Debug, Clone, Default, PartialEq, Serialize, Deserialize)]
275#[serde(rename_all = "SCREAMING_SNAKE_CASE")]
276#[non_exhaustive]
277pub struct StatisticsNameSpec {
278    /// Name of the statistics (提供統計名).
279    #[serde(
280        default,
281        deserialize_with = "de::opt_text",
282        skip_serializing_if = "Option::is_none"
283    )]
284    pub tabulation_category: Option<String>,
285    /// Classification 1 (提供分類名1).
286    #[serde(
287        default,
288        deserialize_with = "de::opt_text",
289        skip_serializing_if = "Option::is_none"
290    )]
291    pub tabulation_sub_category1: Option<String>,
292    /// Classification 2.
293    #[serde(
294        default,
295        deserialize_with = "de::opt_text",
296        skip_serializing_if = "Option::is_none"
297    )]
298    pub tabulation_sub_category2: Option<String>,
299    /// Classification 3.
300    #[serde(
301        default,
302        deserialize_with = "de::opt_text",
303        skip_serializing_if = "Option::is_none"
304    )]
305    pub tabulation_sub_category3: Option<String>,
306    /// Classification 4.
307    #[serde(
308        default,
309        deserialize_with = "de::opt_text",
310        skip_serializing_if = "Option::is_none"
311    )]
312    pub tabulation_sub_category4: Option<String>,
313    /// Classification 5.
314    #[serde(
315        default,
316        deserialize_with = "de::opt_text",
317        skip_serializing_if = "Option::is_none"
318    )]
319    pub tabulation_sub_category5: Option<String>,
320    /// Fields this crate does not know yet, kept as received.
321    #[serde(flatten)]
322    pub extra: Map<String, Value>,
323}
324
325/// `DESCRIPTION` element: explanations of the statistics and classifications.
326#[derive(Debug, Clone, Default, PartialEq, Serialize, Deserialize)]
327#[serde(rename_all = "SCREAMING_SNAKE_CASE")]
328#[non_exhaustive]
329pub struct Description {
330    /// Explanation of the statistics (提供統計の解説).
331    #[serde(
332        default,
333        deserialize_with = "de::opt_text",
334        skip_serializing_if = "Option::is_none"
335    )]
336    pub tabulation_category_explanation: Option<String>,
337    /// Explanation of classification 1.
338    #[serde(
339        default,
340        deserialize_with = "de::opt_text",
341        skip_serializing_if = "Option::is_none"
342    )]
343    pub tabulation_sub_category_explanation1: Option<String>,
344    /// Explanation of classification 2.
345    #[serde(
346        default,
347        deserialize_with = "de::opt_text",
348        skip_serializing_if = "Option::is_none"
349    )]
350    pub tabulation_sub_category_explanation2: Option<String>,
351    /// Explanation of classification 3.
352    #[serde(
353        default,
354        deserialize_with = "de::opt_text",
355        skip_serializing_if = "Option::is_none"
356    )]
357    pub tabulation_sub_category_explanation3: Option<String>,
358    /// Explanation of classification 4.
359    #[serde(
360        default,
361        deserialize_with = "de::opt_text",
362        skip_serializing_if = "Option::is_none"
363    )]
364    pub tabulation_sub_category_explanation4: Option<String>,
365    /// Explanation of classification 5.
366    #[serde(
367        default,
368        deserialize_with = "de::opt_text",
369        skip_serializing_if = "Option::is_none"
370    )]
371    pub tabulation_sub_category_explanation5: Option<String>,
372    /// Fields this crate does not know yet, kept as received.
373    #[serde(flatten)]
374    pub extra: Map<String, Value>,
375}
376
377/// `TITLE_SPEC` element.
378#[derive(Debug, Clone, Default, PartialEq, Serialize, Deserialize)]
379#[serde(rename_all = "SCREAMING_SNAKE_CASE")]
380#[non_exhaustive]
381pub struct TitleSpec {
382    /// Table category (表分類名).
383    #[serde(
384        default,
385        deserialize_with = "de::opt_text",
386        skip_serializing_if = "Option::is_none"
387    )]
388    pub table_category: Option<String>,
389    /// Title (表題).
390    #[serde(
391        default,
392        deserialize_with = "de::opt_text",
393        skip_serializing_if = "Option::is_none"
394    )]
395    pub table_name: Option<String>,
396    /// Explanation of the table (統計表の解説).
397    #[serde(
398        default,
399        deserialize_with = "de::opt_text",
400        skip_serializing_if = "Option::is_none"
401    )]
402    pub table_explanation: Option<String>,
403    /// Title division 1 (表題区分1).
404    #[serde(
405        default,
406        deserialize_with = "de::opt_text",
407        skip_serializing_if = "Option::is_none"
408    )]
409    pub table_sub_category1: Option<String>,
410    /// Title division 2.
411    #[serde(
412        default,
413        deserialize_with = "de::opt_text",
414        skip_serializing_if = "Option::is_none"
415    )]
416    pub table_sub_category2: Option<String>,
417    /// Title division 3.
418    #[serde(
419        default,
420        deserialize_with = "de::opt_text",
421        skip_serializing_if = "Option::is_none"
422    )]
423    pub table_sub_category3: Option<String>,
424    /// Fields this crate does not know yet, kept as received.
425    #[serde(flatten)]
426    pub extra: Map<String, Value>,
427}
428
429/// Response of [`EstatApi::stats_list`](crate::EstatApi::stats_list) (`GET_STATS_LIST`).
430#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
431#[serde(rename_all = "SCREAMING_SNAKE_CASE")]
432#[non_exhaustive]
433pub struct StatsList {
434    /// Outcome of the request.
435    pub result: ApiResult,
436    /// Parameters as e-Stat received them, such as `SEARCH_WORD`.
437    #[serde(default)]
438    pub parameter: Map<String, Value>,
439    /// Tables found. Empty when [`ApiResult::status`] is `1` (no match).
440    #[serde(default, deserialize_with = "de::object_or_default")]
441    pub datalist_inf: DataListInf,
442    /// Fields this crate does not know yet, kept as received.
443    #[serde(flatten)]
444    pub extra: Map<String, Value>,
445}
446
447/// `DATALIST_INF` element.
448#[derive(Debug, Clone, Default, PartialEq, Serialize, Deserialize)]
449#[serde(rename_all = "SCREAMING_SNAKE_CASE")]
450#[non_exhaustive]
451pub struct DataListInf {
452    /// Number of tables (or surveys) matching the conditions.
453    #[serde(default, deserialize_with = "de::number")]
454    pub number: u64,
455    /// Position of the returned rows.
456    #[serde(default, deserialize_with = "de::object_or_default")]
457    pub result_inf: ResultInf,
458    /// Tables.
459    #[serde(
460        default,
461        deserialize_with = "de::one_or_many",
462        skip_serializing_if = "Vec::is_empty"
463    )]
464    pub table_inf: Vec<TableInf>,
465    /// Surveys, when [`stats_name_list`](crate::StatsListParams::stats_name_list) was set.
466    #[serde(
467        default,
468        deserialize_with = "de::one_or_many",
469        skip_serializing_if = "Vec::is_empty"
470    )]
471    pub list_inf: Vec<ListInf>,
472    /// Fields this crate does not know yet, kept as received.
473    #[serde(flatten)]
474    pub extra: Map<String, Value>,
475}
476
477/// `LIST_INF` element: one survey in a survey name list.
478#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
479#[serde(rename_all = "SCREAMING_SNAKE_CASE")]
480#[non_exhaustive]
481pub struct ListInf {
482    /// Government statistics code (`@id`).
483    #[serde(rename = "@id")]
484    pub id: String,
485    /// Survey name with its code.
486    #[serde(
487        default,
488        deserialize_with = "de::object_or_empty",
489        skip_serializing_if = "Option::is_none"
490    )]
491    pub stat_name: Option<CodeName>,
492    /// Agency with its code.
493    #[serde(
494        default,
495        deserialize_with = "de::object_or_empty",
496        skip_serializing_if = "Option::is_none"
497    )]
498    pub gov_org: Option<CodeName>,
499    /// Fields this crate does not know yet, kept as received.
500    #[serde(flatten)]
501    pub extra: Map<String, Value>,
502}
503
504/// Response of [`EstatApi::meta_info`](crate::EstatApi::meta_info) (`GET_META_INFO`).
505#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
506#[serde(rename_all = "SCREAMING_SNAKE_CASE")]
507#[non_exhaustive]
508pub struct MetaInfo {
509    /// Outcome of the request.
510    pub result: ApiResult,
511    /// Parameters as e-Stat received them.
512    #[serde(default)]
513    pub parameter: Map<String, Value>,
514    /// Table and its dimensions.
515    pub metadata_inf: MetadataInf,
516    /// Fields this crate does not know yet, kept as received.
517    #[serde(flatten)]
518    pub extra: Map<String, Value>,
519}
520
521/// `METADATA_INF` element.
522#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
523#[serde(rename_all = "SCREAMING_SNAKE_CASE")]
524#[non_exhaustive]
525pub struct MetadataInf {
526    /// The table.
527    pub table_inf: TableInf,
528    /// Its dimensions and their items.
529    #[serde(default, deserialize_with = "de::object_or_default")]
530    pub class_inf: ClassInf,
531    /// Fields this crate does not know yet, kept as received.
532    #[serde(flatten)]
533    pub extra: Map<String, Value>,
534}
535
536/// `CLASS_INF` element: the dimensions of a table.
537#[derive(Debug, Clone, Default, PartialEq, Serialize, Deserialize)]
538#[serde(rename_all = "SCREAMING_SNAKE_CASE")]
539#[non_exhaustive]
540pub struct ClassInf {
541    /// Request number (`@requestNo`), only in [`StatsDatas`] responses.
542    #[serde(
543        rename = "@requestNo",
544        default,
545        deserialize_with = "de::opt_number",
546        skip_serializing_if = "Option::is_none"
547    )]
548    pub request_no: Option<u32>,
549    /// One entry per dimension (`tab`, `cat01`, `area`, `time`, ...).
550    #[serde(default, deserialize_with = "de::one_or_many")]
551    pub class_obj: Vec<ClassObj>,
552    /// Fields this crate does not know yet, kept as received.
553    #[serde(flatten)]
554    pub extra: Map<String, Value>,
555}
556
557impl ClassInf {
558    /// The entry for a dimension, if the table has it.
559    pub fn get(&self, dim: Dimension) -> Option<&ClassObj> {
560        self.class_obj.iter().find(|obj| obj.id == dim.id())
561    }
562
563    /// Name of the item a value has on a dimension. `None` when the value
564    /// has no code on that dimension or the code is not listed.
565    pub fn label(&self, value: &DataValue, dim: Dimension) -> Option<&str> {
566        let code = value.code(dim)?;
567        self.get(dim)?.find(code).map(|c| c.name.as_str())
568    }
569}
570
571/// `CLASS_OBJ` element: one dimension and its items.
572#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
573#[serde(rename_all = "SCREAMING_SNAKE_CASE")]
574#[non_exhaustive]
575pub struct ClassObj {
576    /// Dimension id (`@id`): `tab`, `time`, `area` or `cat01` to `cat15`.
577    #[serde(rename = "@id")]
578    pub id: String,
579    /// Name (`@name`), such as `地域2012`.
580    #[serde(rename = "@name", default)]
581    pub name: String,
582    /// Explanation (`@description`), when there is one.
583    #[serde(
584        rename = "@description",
585        default,
586        skip_serializing_if = "Option::is_none"
587    )]
588    pub description: Option<String>,
589    /// Explanations of items.
590    #[serde(
591        default,
592        deserialize_with = "de::one_or_many",
593        skip_serializing_if = "Vec::is_empty"
594    )]
595    pub explanation: Vec<Explanation>,
596    /// Items.
597    #[serde(default, deserialize_with = "de::one_or_many")]
598    pub class: Vec<Class>,
599    /// Fields this crate does not know yet, kept as received.
600    #[serde(flatten)]
601    pub extra: Map<String, Value>,
602}
603
604impl ClassObj {
605    /// The item with this code.
606    pub fn find(&self, code: &str) -> Option<&Class> {
607        self.class.iter().find(|class| class.code == code)
608    }
609}
610
611/// `EXPLANATION` element: explanation of one item.
612#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
613#[non_exhaustive]
614pub struct Explanation {
615    /// Item code (`@id`).
616    #[serde(rename = "@id", default)]
617    pub id: String,
618    /// Text.
619    #[serde(rename = "$", default, deserialize_with = "de::text")]
620    pub text: String,
621    /// Fields this crate does not know yet, kept as received.
622    #[serde(flatten)]
623    pub extra: Map<String, Value>,
624}
625
626/// `CLASS` element: one item of a dimension, such as an area or a year.
627#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
628#[non_exhaustive]
629pub struct Class {
630    /// Item code (`@code`), such as `13000`.
631    #[serde(rename = "@code")]
632    pub code: String,
633    /// Name (`@name`), such as `東京都`.
634    #[serde(rename = "@name", default)]
635    pub name: String,
636    /// Hierarchy level (`@level`), from `1`. Often empty for `tab`.
637    #[serde(rename = "@level", default)]
638    pub level: String,
639    /// Unit (`@unit`), such as `人`.
640    #[serde(rename = "@unit", default, skip_serializing_if = "Option::is_none")]
641    pub unit: Option<String>,
642    /// Code of the parent item (`@parentCode`).
643    #[serde(
644        rename = "@parentCode",
645        default,
646        skip_serializing_if = "Option::is_none"
647    )]
648    pub parent_code: Option<String>,
649    /// Additional information (`@addInf`).
650    #[serde(rename = "@addInf", default, skip_serializing_if = "Option::is_none")]
651    pub add_inf: Option<String>,
652    /// Fields this crate does not know yet, kept as received.
653    #[serde(flatten)]
654    pub extra: Map<String, Value>,
655}
656
657/// Response of [`EstatApi::stats_data`](crate::EstatApi::stats_data) (`GET_STATS_DATA`).
658#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
659#[serde(rename_all = "SCREAMING_SNAKE_CASE")]
660#[non_exhaustive]
661pub struct StatsData {
662    /// Outcome of the request. Status `1` means no value matched.
663    pub result: ApiResult,
664    /// Parameters as e-Stat received them.
665    #[serde(default)]
666    pub parameter: Map<String, Value>,
667    /// The table, its dimensions and the values.
668    pub statistical_data: StatisticalData,
669    /// Fields this crate does not know yet, kept as received.
670    #[serde(flatten)]
671    pub extra: Map<String, Value>,
672}
673
674impl StatsData {
675    /// The values.
676    pub fn values(&self) -> &[DataValue] {
677        &self.statistical_data.data_inf.value
678    }
679
680    /// `startPosition` of the next page, `None` on the last page.
681    pub fn next_key(&self) -> Option<u64> {
682        self.statistical_data.result_inf.next_key
683    }
684
685    /// Name of the item a value has on a dimension, looked up in
686    /// [`class_inf`](StatisticalData::class_inf). `None` when the metadata
687    /// was not requested or the value has no code on that dimension.
688    pub fn label(&self, value: &DataValue, dim: Dimension) -> Option<&str> {
689        self.statistical_data.class_inf.as_ref()?.label(value, dim)
690    }
691}
692
693/// `STATISTICAL_DATA` element.
694#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
695#[serde(rename_all = "SCREAMING_SNAKE_CASE")]
696#[non_exhaustive]
697pub struct StatisticalData {
698    /// Number and position of the returned values.
699    #[serde(default, deserialize_with = "de::object_or_default")]
700    pub result_inf: ResultInf,
701    /// The table.
702    pub table_inf: TableInf,
703    /// Dimensions and the items that appear in the values. `None` with
704    /// [`meta(false)`](crate::StatsDataParams::meta).
705    #[serde(
706        default,
707        deserialize_with = "de::object_or_empty",
708        skip_serializing_if = "Option::is_none"
709    )]
710    pub class_inf: Option<ClassInf>,
711    /// Values. Empty when nothing matched or with
712    /// [`count_only`](crate::StatsDataParams::count_only).
713    #[serde(default, deserialize_with = "de::object_or_default")]
714    pub data_inf: DataInf,
715    /// Fields this crate does not know yet, kept as received.
716    #[serde(flatten)]
717    pub extra: Map<String, Value>,
718}
719
720/// Response of [`EstatApi::stats_datas`](crate::EstatApi::stats_datas) (`GET_STATS_DATAS`).
721#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
722#[serde(rename_all = "SCREAMING_SNAKE_CASE")]
723#[non_exhaustive]
724pub struct StatsDatas {
725    /// Outcome of the request. Status `2` means some requests matched nothing;
726    /// the message lists their numbers.
727    pub result: ApiResult,
728    /// Parameters as e-Stat received them, with one `PARAMETER` per request.
729    #[serde(default)]
730    pub parameter_list: Map<String, Value>,
731    /// Tables, metadata and values of all requests.
732    #[serde(default, deserialize_with = "de::object_or_default")]
733    pub statistical_data_list: StatisticalDataList,
734    /// Fields this crate does not know yet, kept as received.
735    #[serde(flatten)]
736    pub extra: Map<String, Value>,
737}
738
739/// `STATISTICAL_DATA_LIST` element. Each entry carries the number of its
740/// request in `request_no`; use [`table`](Self::table),
741/// [`class_inf`](Self::class_inf) and [`values`](Self::values) to pick one.
742#[derive(Debug, Clone, Default, PartialEq, Serialize, Deserialize)]
743#[serde(rename_all = "SCREAMING_SNAKE_CASE")]
744#[non_exhaustive]
745pub struct StatisticalDataList {
746    /// Number of values of all requests together, in `total_number`.
747    #[serde(default, deserialize_with = "de::object_or_default")]
748    pub result_inf: ResultInf,
749    /// Tables, one per request.
750    #[serde(default, deserialize_with = "de::object_or_default")]
751    pub table_inf_list: TableInfList,
752    /// Metadata, one per request. Empty with
753    /// [`meta(false)`](crate::StatsDatasParams::meta).
754    #[serde(default, deserialize_with = "de::object_or_default")]
755    pub class_inf_list: ClassInfList,
756    /// Values, one per request that matched something.
757    #[serde(default, deserialize_with = "de::object_or_default")]
758    pub data_inf_list: DataInfList,
759    /// Fields this crate does not know yet, kept as received.
760    #[serde(flatten)]
761    pub extra: Map<String, Value>,
762}
763
764impl StatisticalDataList {
765    /// Table of a request (numbered from 1).
766    pub fn table(&self, request_no: u32) -> Option<&TableInf> {
767        let tables = &self.table_inf_list.table_inf;
768        tables.iter().find(|t| t.request_no == Some(request_no))
769    }
770
771    /// Metadata of a request.
772    pub fn class_inf(&self, request_no: u32) -> Option<&ClassInf> {
773        let classes = &self.class_inf_list.class_inf;
774        classes.iter().find(|c| c.request_no == Some(request_no))
775    }
776
777    /// Values of a request. Empty when it matched nothing.
778    pub fn values(&self, request_no: u32) -> &[DataValue] {
779        let data = &self.data_inf_list.data_inf;
780        data.iter()
781            .find(|d| d.request_no == Some(request_no))
782            .map_or(&[], |d| d.value.as_slice())
783    }
784}
785
786/// `TABLE_INF_LIST` element.
787#[derive(Debug, Clone, Default, PartialEq, Serialize, Deserialize)]
788#[serde(rename_all = "SCREAMING_SNAKE_CASE")]
789#[non_exhaustive]
790pub struct TableInfList {
791    /// Tables.
792    #[serde(default, deserialize_with = "de::one_or_many")]
793    pub table_inf: Vec<TableInf>,
794    /// Fields this crate does not know yet, kept as received.
795    #[serde(flatten)]
796    pub extra: Map<String, Value>,
797}
798
799/// `CLASS_INF_LIST` element.
800#[derive(Debug, Clone, Default, PartialEq, Serialize, Deserialize)]
801#[serde(rename_all = "SCREAMING_SNAKE_CASE")]
802#[non_exhaustive]
803pub struct ClassInfList {
804    /// Metadata.
805    #[serde(default, deserialize_with = "de::one_or_many")]
806    pub class_inf: Vec<ClassInf>,
807    /// Fields this crate does not know yet, kept as received.
808    #[serde(flatten)]
809    pub extra: Map<String, Value>,
810}
811
812/// `DATA_INF_LIST` element.
813#[derive(Debug, Clone, Default, PartialEq, Serialize, Deserialize)]
814#[serde(rename_all = "SCREAMING_SNAKE_CASE")]
815#[non_exhaustive]
816pub struct DataInfList {
817    /// Values.
818    #[serde(default, deserialize_with = "de::one_or_many")]
819    pub data_inf: Vec<DataInf>,
820    /// Fields this crate does not know yet, kept as received.
821    #[serde(flatten)]
822    pub extra: Map<String, Value>,
823}
824
825/// `DATA_INF` element.
826#[derive(Debug, Clone, Default, PartialEq, Serialize, Deserialize)]
827#[serde(rename_all = "SCREAMING_SNAKE_CASE")]
828#[non_exhaustive]
829pub struct DataInf {
830    /// Request number (`@requestNo`), only in [`StatsDatas`] responses.
831    #[serde(
832        rename = "@requestNo",
833        default,
834        deserialize_with = "de::opt_number",
835        skip_serializing_if = "Option::is_none"
836    )]
837    pub request_no: Option<u32>,
838    /// Meaning of special characters used in place of numbers, such as `X`.
839    #[serde(
840        default,
841        deserialize_with = "de::one_or_many",
842        skip_serializing_if = "Vec::is_empty"
843    )]
844    pub note: Vec<Note>,
845    /// Annotations referred to by [`DataValue::annotation`].
846    #[serde(
847        default,
848        deserialize_with = "de::one_or_many",
849        skip_serializing_if = "Vec::is_empty"
850    )]
851    pub annotation: Vec<Annotation>,
852    /// Values, one per cell.
853    #[serde(default, deserialize_with = "de::one_or_many")]
854    pub value: Vec<DataValue>,
855    /// Fields this crate does not know yet, kept as received.
856    #[serde(flatten)]
857    pub extra: Map<String, Value>,
858}
859
860/// `NOTE` element: a special character and its meaning.
861#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
862#[non_exhaustive]
863pub struct Note {
864    /// The character (`@char`), such as `-`, `X` or `...`.
865    #[serde(rename = "@char", default)]
866    pub char: String,
867    /// Meaning, such as `数字が秘匿されているもの`.
868    #[serde(rename = "$", default, deserialize_with = "de::text")]
869    pub text: String,
870    /// Fields this crate does not know yet, kept as received.
871    #[serde(flatten)]
872    pub extra: Map<String, Value>,
873}
874
875/// `ANNOTATION` element.
876#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
877#[non_exhaustive]
878pub struct Annotation {
879    /// Annotation mark (`@annotation`), such as `J1`.
880    #[serde(rename = "@annotation", default)]
881    pub annotation: String,
882    /// Text.
883    #[serde(rename = "$", default, deserialize_with = "de::text")]
884    pub text: String,
885    /// Fields this crate does not know yet, kept as received.
886    #[serde(flatten)]
887    pub extra: Map<String, Value>,
888}
889
890/// `VALUE` element: one cell of a table.
891///
892/// The value is a string because e-Stat puts special characters such as
893/// `-` or `X` in place of numbers (see [`DataInf::note`]). Use
894/// [`as_f64`](Self::as_f64) for the number.
895#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
896#[non_exhaustive]
897pub struct DataValue {
898    /// Code of the tabulation item (`@tab`).
899    #[serde(rename = "@tab", default, skip_serializing_if = "Option::is_none")]
900    pub tab: Option<String>,
901    /// Code of classification 01 (`@cat01`).
902    #[serde(rename = "@cat01", default, skip_serializing_if = "Option::is_none")]
903    pub cat01: Option<String>,
904    /// Code of classification 02 (`@cat02`).
905    #[serde(rename = "@cat02", default, skip_serializing_if = "Option::is_none")]
906    pub cat02: Option<String>,
907    /// Code of classification 03 (`@cat03`).
908    #[serde(rename = "@cat03", default, skip_serializing_if = "Option::is_none")]
909    pub cat03: Option<String>,
910    /// Code of classification 04 (`@cat04`).
911    #[serde(rename = "@cat04", default, skip_serializing_if = "Option::is_none")]
912    pub cat04: Option<String>,
913    /// Code of classification 05 (`@cat05`).
914    #[serde(rename = "@cat05", default, skip_serializing_if = "Option::is_none")]
915    pub cat05: Option<String>,
916    /// Code of classification 06 (`@cat06`).
917    #[serde(rename = "@cat06", default, skip_serializing_if = "Option::is_none")]
918    pub cat06: Option<String>,
919    /// Code of classification 07 (`@cat07`).
920    #[serde(rename = "@cat07", default, skip_serializing_if = "Option::is_none")]
921    pub cat07: Option<String>,
922    /// Code of classification 08 (`@cat08`).
923    #[serde(rename = "@cat08", default, skip_serializing_if = "Option::is_none")]
924    pub cat08: Option<String>,
925    /// Code of classification 09 (`@cat09`).
926    #[serde(rename = "@cat09", default, skip_serializing_if = "Option::is_none")]
927    pub cat09: Option<String>,
928    /// Code of classification 10 (`@cat10`).
929    #[serde(rename = "@cat10", default, skip_serializing_if = "Option::is_none")]
930    pub cat10: Option<String>,
931    /// Code of classification 11 (`@cat11`).
932    #[serde(rename = "@cat11", default, skip_serializing_if = "Option::is_none")]
933    pub cat11: Option<String>,
934    /// Code of classification 12 (`@cat12`).
935    #[serde(rename = "@cat12", default, skip_serializing_if = "Option::is_none")]
936    pub cat12: Option<String>,
937    /// Code of classification 13 (`@cat13`).
938    #[serde(rename = "@cat13", default, skip_serializing_if = "Option::is_none")]
939    pub cat13: Option<String>,
940    /// Code of classification 14 (`@cat14`).
941    #[serde(rename = "@cat14", default, skip_serializing_if = "Option::is_none")]
942    pub cat14: Option<String>,
943    /// Code of classification 15 (`@cat15`).
944    #[serde(rename = "@cat15", default, skip_serializing_if = "Option::is_none")]
945    pub cat15: Option<String>,
946    /// Area code (`@area`), such as `13000`.
947    #[serde(rename = "@area", default, skip_serializing_if = "Option::is_none")]
948    pub area: Option<String>,
949    /// Time code (`@time`), such as `2020000000`.
950    #[serde(rename = "@time", default, skip_serializing_if = "Option::is_none")]
951    pub time: Option<String>,
952    /// Unit (`@unit`), such as `人`.
953    #[serde(rename = "@unit", default, skip_serializing_if = "Option::is_none")]
954    pub unit: Option<String>,
955    /// Annotation mark (`@annotation`); see [`DataInf::annotation`].
956    #[serde(
957        rename = "@annotation",
958        default,
959        skip_serializing_if = "Option::is_none"
960    )]
961    pub annotation: Option<String>,
962    /// The value as sent, such as `1289100` or `X`.
963    #[serde(rename = "$", default, deserialize_with = "de::text")]
964    pub value: String,
965    /// Fields this crate does not know yet, kept as received.
966    #[serde(flatten)]
967    pub extra: Map<String, Value>,
968}
969
970impl DataValue {
971    /// Code on a dimension, such as `13000` for [`Dimension::Area`].
972    pub fn code(&self, dim: Dimension) -> Option<&str> {
973        let code = match dim {
974            Dimension::Tab => &self.tab,
975            Dimension::Time => &self.time,
976            Dimension::Area => &self.area,
977            Dimension::Cat01 => &self.cat01,
978            Dimension::Cat02 => &self.cat02,
979            Dimension::Cat03 => &self.cat03,
980            Dimension::Cat04 => &self.cat04,
981            Dimension::Cat05 => &self.cat05,
982            Dimension::Cat06 => &self.cat06,
983            Dimension::Cat07 => &self.cat07,
984            Dimension::Cat08 => &self.cat08,
985            Dimension::Cat09 => &self.cat09,
986            Dimension::Cat10 => &self.cat10,
987            Dimension::Cat11 => &self.cat11,
988            Dimension::Cat12 => &self.cat12,
989            Dimension::Cat13 => &self.cat13,
990            Dimension::Cat14 => &self.cat14,
991            Dimension::Cat15 => &self.cat15,
992        };
993        code.as_deref()
994    }
995
996    /// The value as a number. `None` for special characters such as `-` or `X`.
997    pub fn as_f64(&self) -> Option<f64> {
998        self.value
999            .trim()
1000            .parse::<f64>()
1001            .ok()
1002            .filter(|n| n.is_finite())
1003    }
1004}
1005
1006#[cfg(test)]
1007mod tests {
1008    use super::*;
1009    use serde_json::json;
1010
1011    #[test]
1012    fn titles_with_and_without_number() {
1013        let title: Title = serde_json::from_value(json!({"@no": "00100", "$": "人口"})).unwrap();
1014        assert_eq!(title.no.as_deref(), Some("00100"));
1015        assert_eq!(title.name, "人口");
1016        assert_eq!(
1017            serde_json::to_value(&title).unwrap(),
1018            json!({"@no": "00100", "$": "人口"})
1019        );
1020
1021        let title: Title = serde_json::from_value(json!("長期系列")).unwrap();
1022        assert_eq!(title.no, None);
1023        assert_eq!(serde_json::to_value(&title).unwrap(), json!("長期系列"));
1024
1025        let title: Title = serde_json::from_value(json!({"@no": 1, "$": 2020})).unwrap();
1026        assert_eq!((title.no.unwrap(), title.name), ("1".into(), "2020".into()));
1027        let title: Title = serde_json::from_value(json!({"@no": "1"})).unwrap();
1028        assert_eq!(title.name, "");
1029        let title: Title = serde_json::from_value(json!({"$": null})).unwrap();
1030        assert_eq!((title.no, title.name), (None, String::new()));
1031
1032        let error = serde_json::from_value::<Title>(json!([1])).unwrap_err();
1033        assert!(error.to_string().contains("expected a title"));
1034        assert!(serde_json::from_value::<Title>(json!({"@no": true})).is_err());
1035    }
1036
1037    #[test]
1038    fn values_as_numbers() {
1039        let value = |v: Value| -> DataValue { serde_json::from_value(json!({ "$": v })).unwrap() };
1040        assert_eq!(value(json!("1289100")).as_f64(), Some(1289100.0));
1041        assert_eq!(value(json!(" -2.5 ")).as_f64(), Some(-2.5));
1042        assert_eq!(value(json!(12)).as_f64(), Some(12.0));
1043        for special in ["-", "X", "***", "…", "", "NaN", "inf"] {
1044            assert_eq!(value(json!(special)).as_f64(), None, "{special}");
1045        }
1046    }
1047
1048    #[test]
1049    fn codes_by_dimension() {
1050        let mut attributes = Map::new();
1051        for dim in Dimension::ALL {
1052            attributes.insert(format!("@{}", dim.id()), format!("{dim}-code").into());
1053        }
1054        attributes.insert("$".into(), "1".into());
1055        let value: DataValue = serde_json::from_value(Value::Object(attributes.clone())).unwrap();
1056        for dim in Dimension::ALL {
1057            assert_eq!(value.code(dim), Some(format!("{dim}-code").as_str()));
1058        }
1059        assert!(value.extra.is_empty());
1060        assert_eq!(
1061            serde_json::to_value(&value).unwrap(),
1062            Value::Object(attributes)
1063        );
1064
1065        let empty: DataValue = serde_json::from_value(json!({"$": "1"})).unwrap();
1066        assert_eq!(empty.code(Dimension::Area), None);
1067    }
1068}