serde_json/value/
from.rs

1use super::Value;
2use crate::map::Map;
3use crate::number::Number;
4use alloc::borrow::{Cow, ToOwned};
5use alloc::string::String;
6use alloc::vec::Vec;
7
8macro_rules! from_integer {
9    ($($ty:ident)*) => {
10        $(
11            impl From<$ty> for Value {
12                fn from(n: $ty) -> Self {
13                    Value::Number(n.into())
14                }
15            }
16        )*
17    };
18}
19
20from_integer! {
21    i8 i16 i32 i64 isize
22    u8 u16 u32 u64 usize
23}
24
25#[cfg(feature = "arbitrary_precision")]
26from_integer! {
27    i128 u128
28}
29
30impl From<f32> for Value {
31    /// Convert 32-bit floating point number to `Value::Number`, or
32    /// `Value::Null` if infinite or NaN.
33    ///
34    /// # Examples
35    ///
36    /// ```
37    /// use serde_json::Value;
38    ///
39    /// let f: f32 = 13.37;
40    /// let x: Value = f.into();
41    /// ```
42    fn from(f: f32) -> Self {
43        Number::from_f32(f).map_or(Value::Null, Value::Number)
44    }
45}
46
47impl From<f64> for Value {
48    /// Convert 64-bit floating point number to `Value::Number`, or
49    /// `Value::Null` if infinite or NaN.
50    ///
51    /// # Examples
52    ///
53    /// ```
54    /// use serde_json::Value;
55    ///
56    /// let f: f64 = 13.37;
57    /// let x: Value = f.into();
58    /// ```
59    fn from(f: f64) -> Self {
60        Number::from_f64(f).map_or(Value::Null, Value::Number)
61    }
62}
63
64impl From<bool> for Value {
65    /// Convert boolean to `Value::Bool`.
66    ///
67    /// # Examples
68    ///
69    /// ```
70    /// use serde_json::Value;
71    ///
72    /// let b = false;
73    /// let x: Value = b.into();
74    /// ```
75    fn from(f: bool) -> Self {
76        Value::Bool(f)
77    }
78}
79
80impl From<String> for Value {
81    /// Convert `String` to `Value::String`.
82    ///
83    /// # Examples
84    ///
85    /// ```
86    /// use serde_json::Value;
87    ///
88    /// let s: String = "lorem".to_owned();
89    /// let x: Value = s.into();
90    /// ```
91    fn from(f: String) -> Self {
92        Value::String(f)
93    }
94}
95
96impl From<&str> for Value {
97    /// Convert string slice to `Value::String`.
98    ///
99    /// # Examples
100    ///
101    /// ```
102    /// use serde_json::Value;
103    ///
104    /// let s: &str = "lorem";
105    /// let x: Value = s.into();
106    /// ```
107    fn from(f: &str) -> Self {
108        Value::String(f.to_owned())
109    }
110}
111
112impl<'a> From<Cow<'a, str>> for Value {
113    /// Convert copy-on-write string to `Value::String`.
114    ///
115    /// # Examples
116    ///
117    /// ```
118    /// use serde_json::Value;
119    /// use std::borrow::Cow;
120    ///
121    /// let s: Cow<str> = Cow::Borrowed("lorem");
122    /// let x: Value = s.into();
123    /// ```
124    ///
125    /// ```
126    /// use serde_json::Value;
127    /// use std::borrow::Cow;
128    ///
129    /// let s: Cow<str> = Cow::Owned("lorem".to_owned());
130    /// let x: Value = s.into();
131    /// ```
132    fn from(f: Cow<'a, str>) -> Self {
133        Value::String(f.into_owned())
134    }
135}
136
137impl From<Number> for Value {
138    /// Convert `Number` to `Value::Number`.
139    ///
140    /// # Examples
141    ///
142    /// ```
143    /// use serde_json::{Number, Value};
144    ///
145    /// let n = Number::from(7);
146    /// let x: Value = n.into();
147    /// ```
148    fn from(f: Number) -> Self {
149        Value::Number(f)
150    }
151}
152
153impl From<Map<String, Value>> for Value {
154    /// Convert map (with string keys) to `Value::Object`.
155    ///
156    /// # Examples
157    ///
158    /// ```
159    /// use serde_json::{Map, Value};
160    ///
161    /// let mut m = Map::new();
162    /// m.insert("Lorem".to_owned(), "ipsum".into());
163    /// let x: Value = m.into();
164    /// ```
165    fn from(f: Map<String, Value>) -> Self {
166        Value::Object(f)
167    }
168}
169
170impl<T: Into<Value>> From<Vec<T>> for Value {
171    /// Convert a `Vec` to `Value::Array`.
172    ///
173    /// # Examples
174    ///
175    /// ```
176    /// use serde_json::Value;
177    ///
178    /// let v = vec!["lorem", "ipsum", "dolor"];
179    /// let x: Value = v.into();
180    /// ```
181    fn from(f: Vec<T>) -> Self {
182        Value::Array(f.into_iter().map(Into::into).collect())
183    }
184}
185
186impl<T: Into<Value>, const N: usize> From<[T; N]> for Value {
187    fn from(array: [T; N]) -> Self {
188        Value::Array(array.into_iter().map(Into::into).collect())
189    }
190}
191
192impl<T: Clone + Into<Value>> From<&[T]> for Value {
193    /// Convert a slice to `Value::Array`.
194    ///
195    /// # Examples
196    ///
197    /// ```
198    /// use serde_json::Value;
199    ///
200    /// let v: &[&str] = &["lorem", "ipsum", "dolor"];
201    /// let x: Value = v.into();
202    /// ```
203    fn from(f: &[T]) -> Self {
204        Value::Array(f.iter().cloned().map(Into::into).collect())
205    }
206}
207
208impl<T: Into<Value>> FromIterator<T> for Value {
209    /// Create a `Value::Array` by collecting an iterator of array elements.
210    ///
211    /// # Examples
212    ///
213    /// ```
214    /// use serde_json::Value;
215    ///
216    /// let v = std::iter::repeat(42).take(5);
217    /// let x: Value = v.collect();
218    /// ```
219    ///
220    /// ```
221    /// use serde_json::Value;
222    ///
223    /// let v: Vec<_> = vec!["lorem", "ipsum", "dolor"];
224    /// let x: Value = v.into_iter().collect();
225    /// ```
226    ///
227    /// ```
228    /// use std::iter::FromIterator;
229    /// use serde_json::Value;
230    ///
231    /// let x: Value = Value::from_iter(vec!["lorem", "ipsum", "dolor"]);
232    /// ```
233    fn from_iter<I: IntoIterator<Item = T>>(iter: I) -> Self {
234        Value::Array(iter.into_iter().map(Into::into).collect())
235    }
236}
237
238impl<K: Into<String>, V: Into<Value>> FromIterator<(K, V)> for Value {
239    /// Create a `Value::Object` by collecting an iterator of key-value pairs.
240    ///
241    /// # Examples
242    ///
243    /// ```
244    /// use serde_json::Value;
245    ///
246    /// let v: Vec<_> = vec![("lorem", 40), ("ipsum", 2)];
247    /// let x: Value = v.into_iter().collect();
248    /// ```
249    fn from_iter<I: IntoIterator<Item = (K, V)>>(iter: I) -> Self {
250        Value::Object(
251            iter.into_iter()
252                .map(|(k, v)| (k.into(), v.into()))
253                .collect(),
254        )
255    }
256}
257
258impl From<()> for Value {
259    /// Convert `()` to `Value::Null`.
260    ///
261    /// # Examples
262    ///
263    /// ```
264    /// use serde_json::Value;
265    ///
266    /// let u = ();
267    /// let x: Value = u.into();
268    /// ```
269    fn from((): ()) -> Self {
270        Value::Null
271    }
272}
273
274impl<T> From<Option<T>> for Value
275where
276    T: Into<Value>,
277{
278    fn from(opt: Option<T>) -> Self {
279        match opt {
280            None => Value::Null,
281            Some(value) => Into::into(value),
282        }
283    }
284}