| 1 |
//! The Value enum, a loosely typed way of representing any valid JSON value. |
| 2 |
//! |
| 3 |
//! # Constructing JSON |
| 4 |
//! |
| 5 |
//! Serde JSON provides a [`json!` macro][macro] to build `serde_json::Value` |
| 6 |
//! objects with very natural JSON syntax. |
| 7 |
//! |
| 8 |
//! ``` |
| 9 |
//! use serde_json::json; |
| 10 |
//! |
| 11 |
//! fn main() { |
| 12 |
//! // The type of `john` is `serde_json::Value` |
| 13 |
//! let john = json!({ |
| 14 |
//! "name": "John Doe", |
| 15 |
//! "age": 43, |
| 16 |
//! "phones": [ |
| 17 |
//! "+44 1234567", |
| 18 |
//! "+44 2345678" |
| 19 |
//! ] |
| 20 |
//! }); |
| 21 |
//! |
| 22 |
//! println!("first phone number: {}", john["phones"][0]); |
| 23 |
//! |
| 24 |
//! // Convert to a string of JSON and print it out |
| 25 |
//! println!("{}", john.to_string()); |
| 26 |
//! } |
| 27 |
//! ``` |
| 28 |
//! |
| 29 |
//! The `Value::to_string()` function converts a `serde_json::Value` into a |
| 30 |
//! `String` of JSON text. |
| 31 |
//! |
| 32 |
//! One neat thing about the `json!` macro is that variables and expressions can |
| 33 |
//! be interpolated directly into the JSON value as you are building it. Serde |
| 34 |
//! will check at compile time that the value you are interpolating is able to |
| 35 |
//! be represented as JSON. |
| 36 |
//! |
| 37 |
//! ``` |
| 38 |
//! # use serde_json::json; |
| 39 |
//! # |
| 40 |
//! # fn random_phone() -> u16 { 0 } |
| 41 |
//! # |
| 42 |
//! let full_name = "John Doe"; |
| 43 |
//! let age_last_year = 42; |
| 44 |
//! |
| 45 |
//! // The type of `john` is `serde_json::Value` |
| 46 |
//! let john = json!({ |
| 47 |
//! "name": full_name, |
| 48 |
//! "age": age_last_year + 1, |
| 49 |
//! "phones": [ |
| 50 |
//! format!("+44 {}", random_phone()) |
| 51 |
//! ] |
| 52 |
//! }); |
| 53 |
//! ``` |
| 54 |
//! |
| 55 |
//! A string of JSON data can be parsed into a `serde_json::Value` by the |
| 56 |
//! [`serde_json::from_str`][from_str] function. There is also |
| 57 |
//! [`from_slice`][from_slice] for parsing from a byte slice `&[u8]` and |
| 58 |
//! [`from_reader`][from_reader] for parsing from any `io::Read` like a File or |
| 59 |
//! a TCP stream. |
| 60 |
//! |
| 61 |
//! ``` |
| 62 |
//! use serde_json::{json, Value, Error}; |
| 63 |
//! |
| 64 |
//! fn untyped_example() -> Result<(), Error> { |
| 65 |
//! // Some JSON input data as a &str. Maybe this comes from the user. |
| 66 |
//! let data = r#" |
| 67 |
//! { |
| 68 |
//! "name": "John Doe", |
| 69 |
//! "age": 43, |
| 70 |
//! "phones": [ |
| 71 |
//! "+44 1234567", |
| 72 |
//! "+44 2345678" |
| 73 |
//! ] |
| 74 |
//! }"#; |
| 75 |
//! |
| 76 |
//! // Parse the string of data into serde_json::Value. |
| 77 |
//! let v: Value = serde_json::from_str(data)?; |
| 78 |
//! |
| 79 |
//! // Access parts of the data by indexing with square brackets. |
| 80 |
//! println!("Please call {} at the number {}", v["name"], v["phones"][0]); |
| 81 |
//! |
| 82 |
//! Ok(()) |
| 83 |
//! } |
| 84 |
//! # |
| 85 |
//! # untyped_example().unwrap(); |
| 86 |
//! ``` |
| 87 |
//! |
| 88 |
//! [macro]: crate::json |
| 89 |
//! [from_str]: crate::de::from_str |
| 90 |
//! [from_slice]: crate::de::from_slice |
| 91 |
//! [from_reader]: crate::de::from_reader |
| 92 |
|
| 93 |
use crate::error::Error; |
| 94 |
use crate::io; |
| 95 |
use alloc::string::String; |
| 96 |
use alloc::vec::Vec; |
| 97 |
use core::fmt::{self, Debug, Display}; |
| 98 |
use core::mem; |
| 99 |
use core::str; |
| 100 |
use serde::de::DeserializeOwned; |
| 101 |
use serde::ser::Serialize; |
| 102 |
|
| 103 |
pub use self::index::Index; |
| 104 |
pub use self::ser::Serializer; |
| 105 |
pub use crate::map::Map; |
| 106 |
pub use crate::number::Number; |
| 107 |
|
| 108 |
#[cfg(feature = "raw_value")] |
| 109 |
#[cfg_attr(docsrs, doc(cfg(feature = "raw_value")))] |
| 110 |
pub use crate::raw::{to_raw_value, RawValue}; |
| 111 |
|
| 112 |
/// Represents any valid JSON value. |
| 113 |
/// |
| 114 |
/// See the [`serde_json::value` module documentation](self) for usage examples. |
| 115 |
#[derive(Clone, Eq, PartialEq)] |
| 116 |
pub enum Value { |
| 117 |
/// Represents a JSON null value. |
| 118 |
/// |
| 119 |
/// ``` |
| 120 |
/// # use serde_json::json; |
| 121 |
/// # |
| 122 |
/// let v = json!(null); |
| 123 |
/// ``` |
| 124 |
Null, |
| 125 |
|
| 126 |
/// Represents a JSON boolean. |
| 127 |
/// |
| 128 |
/// ``` |
| 129 |
/// # use serde_json::json; |
| 130 |
/// # |
| 131 |
/// let v = json!(true); |
| 132 |
/// ``` |
| 133 |
Bool(bool), |
| 134 |
|
| 135 |
/// Represents a JSON number, whether integer or floating point. |
| 136 |
/// |
| 137 |
/// ``` |
| 138 |
/// # use serde_json::json; |
| 139 |
/// # |
| 140 |
/// let v = json!(12.5); |
| 141 |
/// ``` |
| 142 |
Number(Number), |
| 143 |
|
| 144 |
/// Represents a JSON string. |
| 145 |
/// |
| 146 |
/// ``` |
| 147 |
/// # use serde_json::json; |
| 148 |
/// # |
| 149 |
/// let v = json!("a string"); |
| 150 |
/// ``` |
| 151 |
String(String), |
| 152 |
|
| 153 |
/// Represents a JSON array. |
| 154 |
/// |
| 155 |
/// ``` |
| 156 |
/// # use serde_json::json; |
| 157 |
/// # |
| 158 |
/// let v = json!(["an", "array"]); |
| 159 |
/// ``` |
| 160 |
Array(Vec<Value>), |
| 161 |
|
| 162 |
/// Represents a JSON object. |
| 163 |
/// |
| 164 |
/// By default the map is backed by a BTreeMap. Enable the `preserve_order` |
| 165 |
/// feature of serde_json to use IndexMap instead, which preserves |
| 166 |
/// entries in the order they are inserted into the map. In particular, this |
| 167 |
/// allows JSON data to be deserialized into a Value and serialized to a |
| 168 |
/// string while retaining the order of map keys in the input. |
| 169 |
/// |
| 170 |
/// ``` |
| 171 |
/// # use serde_json::json; |
| 172 |
/// # |
| 173 |
/// let v = json!({ "an": "object" }); |
| 174 |
/// ``` |
| 175 |
Object(Map<String, Value>), |
| 176 |
} |
| 177 |
|
| 178 |
impl Debug for Value { |
| 179 |
fn fmt(&self, formatter: &mut fmt::Formatter) -> fmt::Result { |
| 180 |
match self { |
| 181 |
Value::Null => formatter.write_str("Null"), |
| 182 |
Value::Bool(boolean) => write!(formatter, "Bool({})", boolean), |
| 183 |
Value::Number(number) => Debug::fmt(number, formatter), |
| 184 |
Value::String(string) => write!(formatter, "String({:?})", string), |
| 185 |
Value::Array(vec) => { |
| 186 |
tri!(formatter.write_str("Array ")); |
| 187 |
Debug::fmt(vec, formatter) |
| 188 |
} |
| 189 |
Value::Object(map) => { |
| 190 |
tri!(formatter.write_str("Object ")); |
| 191 |
Debug::fmt(map, formatter) |
| 192 |
} |
| 193 |
} |
| 194 |
} |
| 195 |
} |
| 196 |
|
| 197 |
impl Display for Value { |
| 198 |
/// Display a JSON value as a string. |
| 199 |
/// |
| 200 |
/// ``` |
| 201 |
/// # use serde_json::json; |
| 202 |
/// # |
| 203 |
/// let json = json!({ "city": "London", "street": "10 Downing Street" }); |
| 204 |
/// |
| 205 |
/// // Compact format: |
| 206 |
/// // |
| 207 |
/// // {"city":"London","street":"10 Downing Street"} |
| 208 |
/// let compact = format!("{}", json); |
| 209 |
/// assert_eq!(compact, |
| 210 |
/// "{\"city\":\"London\",\"street\":\"10 Downing Street\"}"); |
| 211 |
/// |
| 212 |
/// // Pretty format: |
| 213 |
/// // |
| 214 |
/// // { |
| 215 |
/// // "city": "London", |
| 216 |
/// // "street": "10 Downing Street" |
| 217 |
/// // } |
| 218 |
/// let pretty = format!("{:#}", json); |
| 219 |
/// assert_eq!(pretty, |
| 220 |
/// "{\n \"city\": \"London\",\n \"street\": \"10 Downing Street\"\n}"); |
| 221 |
/// ``` |
| 222 |
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { |
| 223 |
struct WriterFormatter<'a, 'b: 'a> { |
| 224 |
inner: &'a mut fmt::Formatter<'b>, |
| 225 |
} |
| 226 |
|
| 227 |
impl<'a, 'b> io::Write for WriterFormatter<'a, 'b> { |
| 228 |
fn write(&mut self, buf: &[u8]) -> io::Result<usize> { |
| 229 |
// Safety: the serializer below only emits valid utf8 when using |
| 230 |
// the default formatter. |
| 231 |
let s = unsafe { str::from_utf8_unchecked(buf) }; |
| 232 |
tri!(self.inner.write_str(s).map_err(io_error)); |
| 233 |
Ok(buf.len()) |
| 234 |
} |
| 235 |
|
| 236 |
fn flush(&mut self) -> io::Result<()> { |
| 237 |
Ok(()) |
| 238 |
} |
| 239 |
} |
| 240 |
|
| 241 |
fn io_error(_: fmt::Error) -> io::Error { |
| 242 |
// Error value does not matter because Display impl just maps it |
| 243 |
// back to fmt::Error. |
| 244 |
io::Error::new(io::ErrorKind::Other, "fmt error") |
| 245 |
} |
| 246 |
|
| 247 |
let alternate = f.alternate(); |
| 248 |
let mut wr = WriterFormatter { inner: f }; |
| 249 |
if alternate { |
| 250 |
// {:#} |
| 251 |
super::ser::to_writer_pretty(&mut wr, self).map_err(|_| fmt::Error) |
| 252 |
} else { |
| 253 |
// {} |
| 254 |
super::ser::to_writer(&mut wr, self).map_err(|_| fmt::Error) |
| 255 |
} |
| 256 |
} |
| 257 |
} |
| 258 |
|
| 259 |
fn parse_index(s: &str) -> Option<usize> { |
| 260 |
if s.starts_with('+') || (s.starts_with('0') && s.len() != 1) { |
| 261 |
return None; |
| 262 |
} |
| 263 |
s.parse().ok() |
| 264 |
} |
| 265 |
|
| 266 |
impl Value { |
| 267 |
/// Index into a JSON array or map. A string index can be used to access a |
| 268 |
/// value in a map, and a usize index can be used to access an element of an |
| 269 |
/// array. |
| 270 |
/// |
| 271 |
/// Returns `None` if the type of `self` does not match the type of the |
| 272 |
/// index, for example if the index is a string and `self` is an array or a |
| 273 |
/// number. Also returns `None` if the given key does not exist in the map |
| 274 |
/// or the given index is not within the bounds of the array. |
| 275 |
/// |
| 276 |
/// ``` |
| 277 |
/// # use serde_json::json; |
| 278 |
/// # |
| 279 |
/// let object = json!({ "A": 65, "B": 66, "C": 67 }); |
| 280 |
/// assert_eq!(*object.get("A").unwrap(), json!(65)); |
| 281 |
/// |
| 282 |
/// let array = json!([ "A", "B", "C" ]); |
| 283 |
/// assert_eq!(*array.get(2).unwrap(), json!("C")); |
| 284 |
/// |
| 285 |
/// assert_eq!(array.get("A"), None); |
| 286 |
/// ``` |
| 287 |
/// |
| 288 |
/// Square brackets can also be used to index into a value in a more concise |
| 289 |
/// way. This returns `Value::Null` in cases where `get` would have returned |
| 290 |
/// `None`. |
| 291 |
/// |
| 292 |
/// ``` |
| 293 |
/// # use serde_json::json; |
| 294 |
/// # |
| 295 |
/// let object = json!({ |
| 296 |
/// "A": ["a", "á", "à"], |
| 297 |
/// "B": ["b", "b́"], |
| 298 |
/// "C": ["c", "ć", "ć̣", "ḉ"], |
| 299 |
/// }); |
| 300 |
/// assert_eq!(object["B"][0], json!("b")); |
| 301 |
/// |
| 302 |
/// assert_eq!(object["D"], json!(null)); |
| 303 |
/// assert_eq!(object[0]["x"]["y"]["z"], json!(null)); |
| 304 |
/// ``` |
| 305 |
pub fn get<I: Index>(&self, index: I) -> Option<&Value> { |
| 306 |
index.index_into(self) |
| 307 |
} |
| 308 |
|
| 309 |
/// Mutably index into a JSON array or map. A string index can be used to |
| 310 |
/// access a value in a map, and a usize index can be used to access an |
| 311 |
/// element of an array. |
| 312 |
/// |
| 313 |
/// Returns `None` if the type of `self` does not match the type of the |
| 314 |
/// index, for example if the index is a string and `self` is an array or a |
| 315 |
/// number. Also returns `None` if the given key does not exist in the map |
| 316 |
/// or the given index is not within the bounds of the array. |
| 317 |
/// |
| 318 |
/// ``` |
| 319 |
/// # use serde_json::json; |
| 320 |
/// # |
| 321 |
/// let mut object = json!({ "A": 65, "B": 66, "C": 67 }); |
| 322 |
/// *object.get_mut("A").unwrap() = json!(69); |
| 323 |
/// |
| 324 |
/// let mut array = json!([ "A", "B", "C" ]); |
| 325 |
/// *array.get_mut(2).unwrap() = json!("D"); |
| 326 |
/// ``` |
| 327 |
pub fn get_mut<I: Index>(&mut self, index: I) -> Option<&mut Value> { |
| 328 |
index.index_into_mut(self) |
| 329 |
} |
| 330 |
|
| 331 |
/// Returns true if the `Value` is an Object. Returns false otherwise. |
| 332 |
/// |
| 333 |
/// For any Value on which `is_object` returns true, `as_object` and |
| 334 |
/// `as_object_mut` are guaranteed to return the map representation of the |
| 335 |
/// object. |
| 336 |
/// |
| 337 |
/// ``` |
| 338 |
/// # use serde_json::json; |
| 339 |
/// # |
| 340 |
/// let obj = json!({ "a": { "nested": true }, "b": ["an", "array"] }); |
| 341 |
/// |
| 342 |
/// assert!(obj.is_object()); |
| 343 |
/// assert!(obj["a"].is_object()); |
| 344 |
/// |
| 345 |
/// // array, not an object |
| 346 |
/// assert!(!obj["b"].is_object()); |
| 347 |
/// ``` |
| 348 |
pub fn is_object(&self) -> bool { |
| 349 |
self.as_object().is_some() |
| 350 |
} |
| 351 |
|
| 352 |
/// If the `Value` is an Object, returns the associated Map. Returns None |
| 353 |
/// otherwise. |
| 354 |
/// |
| 355 |
/// ``` |
| 356 |
/// # use serde_json::json; |
| 357 |
/// # |
| 358 |
/// let v = json!({ "a": { "nested": true }, "b": ["an", "array"] }); |
| 359 |
/// |
| 360 |
/// // The length of `{"nested": true}` is 1 entry. |
| 361 |
/// assert_eq!(v["a"].as_object().unwrap().len(), 1); |
| 362 |
/// |
| 363 |
/// // The array `["an", "array"]` is not an object. |
| 364 |
/// assert_eq!(v["b"].as_object(), None); |
| 365 |
/// ``` |
| 366 |
pub fn as_object(&self) -> Option<&Map<String, Value>> { |
| 367 |
match self { |
| 368 |
Value::Object(map) => Some(map), |
| 369 |
_ => None, |
| 370 |
} |
| 371 |
} |
| 372 |
|
| 373 |
/// If the `Value` is an Object, returns the associated mutable Map. |
| 374 |
/// Returns None otherwise. |
| 375 |
/// |
| 376 |
/// ``` |
| 377 |
/// # use serde_json::json; |
| 378 |
/// # |
| 379 |
/// let mut v = json!({ "a": { "nested": true } }); |
| 380 |
/// |
| 381 |
/// v["a"].as_object_mut().unwrap().clear(); |
| 382 |
/// assert_eq!(v, json!({ "a": {} })); |
| 383 |
/// ``` |
| 384 |
pub fn as_object_mut(&mut self) -> Option<&mut Map<String, Value>> { |
| 385 |
match self { |
| 386 |
Value::Object(map) => Some(map), |
| 387 |
_ => None, |
| 388 |
} |
| 389 |
} |
| 390 |
|
| 391 |
/// Returns true if the `Value` is an Array. Returns false otherwise. |
| 392 |
/// |
| 393 |
/// For any Value on which `is_array` returns true, `as_array` and |
| 394 |
/// `as_array_mut` are guaranteed to return the vector representing the |
| 395 |
/// array. |
| 396 |
/// |
| 397 |
/// ``` |
| 398 |
/// # use serde_json::json; |
| 399 |
/// # |
| 400 |
/// let obj = json!({ "a": ["an", "array"], "b": { "an": "object" } }); |
| 401 |
/// |
| 402 |
/// assert!(obj["a"].is_array()); |
| 403 |
/// |
| 404 |
/// // an object, not an array |
| 405 |
/// assert!(!obj["b"].is_array()); |
| 406 |
/// ``` |
| 407 |
pub fn is_array(&self) -> bool { |
| 408 |
self.as_array().is_some() |
| 409 |
} |
| 410 |
|
| 411 |
/// If the `Value` is an Array, returns the associated vector. Returns None |
| 412 |
/// otherwise. |
| 413 |
/// |
| 414 |
/// ``` |
| 415 |
/// # use serde_json::json; |
| 416 |
/// # |
| 417 |
/// let v = json!({ "a": ["an", "array"], "b": { "an": "object" } }); |
| 418 |
/// |
| 419 |
/// // The length of `["an", "array"]` is 2 elements. |
| 420 |
/// assert_eq!(v["a"].as_array().unwrap().len(), 2); |
| 421 |
/// |
| 422 |
/// // The object `{"an": "object"}` is not an array. |
| 423 |
/// assert_eq!(v["b"].as_array(), None); |
| 424 |
/// ``` |
| 425 |
pub fn as_array(&self) -> Option<&Vec<Value>> { |
| 426 |
match self { |
| 427 |
Value::Array(array) => Some(array), |
| 428 |
_ => None, |
| 429 |
} |
| 430 |
} |
| 431 |
|
| 432 |
/// If the `Value` is an Array, returns the associated mutable vector. |
| 433 |
/// Returns None otherwise. |
| 434 |
/// |
| 435 |
/// ``` |
| 436 |
/// # use serde_json::json; |
| 437 |
/// # |
| 438 |
/// let mut v = json!({ "a": ["an", "array"] }); |
| 439 |
/// |
| 440 |
/// v["a"].as_array_mut().unwrap().clear(); |
| 441 |
/// assert_eq!(v, json!({ "a": [] })); |
| 442 |
/// ``` |
| 443 |
pub fn as_array_mut(&mut self) -> Option<&mut Vec<Value>> { |
| 444 |
match self { |
| 445 |
Value::Array(list) => Some(list), |
| 446 |
_ => None, |
| 447 |
} |
| 448 |
} |
| 449 |
|
| 450 |
/// Returns true if the `Value` is a String. Returns false otherwise. |
| 451 |
/// |
| 452 |
/// For any Value on which `is_string` returns true, `as_str` is guaranteed |
| 453 |
/// to return the string slice. |
| 454 |
/// |
| 455 |
/// ``` |
| 456 |
/// # use serde_json::json; |
| 457 |
/// # |
| 458 |
/// let v = json!({ "a": "some string", "b": false }); |
| 459 |
/// |
| 460 |
/// assert!(v["a"].is_string()); |
| 461 |
/// |
| 462 |
/// // The boolean `false` is not a string. |
| 463 |
/// assert!(!v["b"].is_string()); |
| 464 |
/// ``` |
| 465 |
pub fn is_string(&self) -> bool { |
| 466 |
self.as_str().is_some() |
| 467 |
} |
| 468 |
|
| 469 |
/// If the `Value` is a String, returns the associated str. Returns None |
| 470 |
/// otherwise. |
| 471 |
/// |
| 472 |
/// ``` |
| 473 |
/// # use serde_json::json; |
| 474 |
/// # |
| 475 |
/// let v = json!({ "a": "some string", "b": false }); |
| 476 |
/// |
| 477 |
/// assert_eq!(v["a"].as_str(), Some("some string")); |
| 478 |
/// |
| 479 |
/// // The boolean `false` is not a string. |
| 480 |
/// assert_eq!(v["b"].as_str(), None); |
| 481 |
/// |
| 482 |
/// // JSON values are printed in JSON representation, so strings are in quotes. |
| 483 |
/// // |
| 484 |
/// // The value is: "some string" |
| 485 |
/// println!("The value is: {}", v["a"]); |
| 486 |
/// |
| 487 |
/// // Rust strings are printed without quotes. |
| 488 |
/// // |
| 489 |
/// // The value is: some string |
| 490 |
/// println!("The value is: {}", v["a"].as_str().unwrap()); |
| 491 |
/// ``` |
| 492 |
pub fn as_str(&self) -> Option<&str> { |
| 493 |
match self { |
| 494 |
Value::String(s) => Some(s), |
| 495 |
_ => None, |
| 496 |
} |
| 497 |
} |
| 498 |
|
| 499 |
/// Returns true if the `Value` is a Number. Returns false otherwise. |
| 500 |
/// |
| 501 |
/// ``` |
| 502 |
/// # use serde_json::json; |
| 503 |
/// # |
| 504 |
/// let v = json!({ "a": 1, "b": "2" }); |
| 505 |
/// |
| 506 |
/// assert!(v["a"].is_number()); |
| 507 |
/// |
| 508 |
/// // The string `"2"` is a string, not a number. |
| 509 |
/// assert!(!v["b"].is_number()); |
| 510 |
/// ``` |
| 511 |
pub fn is_number(&self) -> bool { |
| 512 |
match *self { |
| 513 |
Value::Number(_) => true, |
| 514 |
_ => false, |
| 515 |
} |
| 516 |
} |
| 517 |
|
| 518 |
/// If the `Value` is a Number, returns the associated [`Number`]. Returns |
| 519 |
/// None otherwise. |
| 520 |
/// |
| 521 |
/// ``` |
| 522 |
/// # use serde_json::{json, Number}; |
| 523 |
/// # |
| 524 |
/// let v = json!({ "a": 1, "b": 2.2, "c": -3, "d": "4" }); |
| 525 |
/// |
| 526 |
/// assert_eq!(v["a"].as_number(), Some(&Number::from(1u64))); |
| 527 |
/// assert_eq!(v["b"].as_number(), Some(&Number::from_f64(2.2).unwrap())); |
| 528 |
/// assert_eq!(v["c"].as_number(), Some(&Number::from(-3i64))); |
| 529 |
/// |
| 530 |
/// // The string `"4"` is not a number. |
| 531 |
/// assert_eq!(v["d"].as_number(), None); |
| 532 |
/// ``` |
| 533 |
pub fn as_number(&self) -> Option<&Number> { |
| 534 |
match self { |
| 535 |
Value::Number(number) => Some(number), |
| 536 |
_ => None, |
| 537 |
} |
| 538 |
} |
| 539 |
|
| 540 |
/// Returns true if the `Value` is an integer between `i64::MIN` and |
| 541 |
/// `i64::MAX`. |
| 542 |
/// |
| 543 |
/// For any Value on which `is_i64` returns true, `as_i64` is guaranteed to |
| 544 |
/// return the integer value. |
| 545 |
/// |
| 546 |
/// ``` |
| 547 |
/// # use serde_json::json; |
| 548 |
/// # |
| 549 |
/// let big = i64::max_value() as u64 + 10; |
| 550 |
/// let v = json!({ "a": 64, "b": big, "c": 256.0 }); |
| 551 |
/// |
| 552 |
/// assert!(v["a"].is_i64()); |
| 553 |
/// |
| 554 |
/// // Greater than i64::MAX. |
| 555 |
/// assert!(!v["b"].is_i64()); |
| 556 |
/// |
| 557 |
/// // Numbers with a decimal point are not considered integers. |
| 558 |
/// assert!(!v["c"].is_i64()); |
| 559 |
/// ``` |
| 560 |
pub fn is_i64(&self) -> bool { |
| 561 |
match self { |
| 562 |
Value::Number(n) => n.is_i64(), |
| 563 |
_ => false, |
| 564 |
} |
| 565 |
} |
| 566 |
|
| 567 |
/// Returns true if the `Value` is an integer between zero and `u64::MAX`. |
| 568 |
/// |
| 569 |
/// For any Value on which `is_u64` returns true, `as_u64` is guaranteed to |
| 570 |
/// return the integer value. |
| 571 |
/// |
| 572 |
/// ``` |
| 573 |
/// # use serde_json::json; |
| 574 |
/// # |
| 575 |
/// let v = json!({ "a": 64, "b": -64, "c": 256.0 }); |
| 576 |
/// |
| 577 |
/// assert!(v["a"].is_u64()); |
| 578 |
/// |
| 579 |
/// // Negative integer. |
| 580 |
/// assert!(!v["b"].is_u64()); |
| 581 |
/// |
| 582 |
/// // Numbers with a decimal point are not considered integers. |
| 583 |
/// assert!(!v["c"].is_u64()); |
| 584 |
/// ``` |
| 585 |
pub fn is_u64(&self) -> bool { |
| 586 |
match self { |
| 587 |
Value::Number(n) => n.is_u64(), |
| 588 |
_ => false, |
| 589 |
} |
| 590 |
} |
| 591 |
|
| 592 |
/// Returns true if the `Value` is a number that can be represented by f64. |
| 593 |
/// |
| 594 |
/// For any Value on which `is_f64` returns true, `as_f64` is guaranteed to |
| 595 |
/// return the floating point value. |
| 596 |
/// |
| 597 |
/// Currently this function returns true if and only if both `is_i64` and |
| 598 |
/// `is_u64` return false but this is not a guarantee in the future. |
| 599 |
/// |
| 600 |
/// ``` |
| 601 |
/// # use serde_json::json; |
| 602 |
/// # |
| 603 |
/// let v = json!({ "a": 256.0, "b": 64, "c": -64 }); |
| 604 |
/// |
| 605 |
/// assert!(v["a"].is_f64()); |
| 606 |
/// |
| 607 |
/// // Integers. |
| 608 |
/// assert!(!v["b"].is_f64()); |
| 609 |
/// assert!(!v["c"].is_f64()); |
| 610 |
/// ``` |
| 611 |
pub fn is_f64(&self) -> bool { |
| 612 |
match self { |
| 613 |
Value::Number(n) => n.is_f64(), |
| 614 |
_ => false, |
| 615 |
} |
| 616 |
} |
| 617 |
|
| 618 |
/// If the `Value` is an integer, represent it as i64 if possible. Returns |
| 619 |
/// None otherwise. |
| 620 |
/// |
| 621 |
/// ``` |
| 622 |
/// # use serde_json::json; |
| 623 |
/// # |
| 624 |
/// let big = i64::max_value() as u64 + 10; |
| 625 |
/// let v = json!({ "a": 64, "b": big, "c": 256.0 }); |
| 626 |
/// |
| 627 |
/// assert_eq!(v["a"].as_i64(), Some(64)); |
| 628 |
/// assert_eq!(v["b"].as_i64(), None); |
| 629 |
/// assert_eq!(v["c"].as_i64(), None); |
| 630 |
/// ``` |
| 631 |
pub fn as_i64(&self) -> Option<i64> { |
| 632 |
match self { |
| 633 |
Value::Number(n) => n.as_i64(), |
| 634 |
_ => None, |
| 635 |
} |
| 636 |
} |
| 637 |
|
| 638 |
/// If the `Value` is an integer, represent it as u64 if possible. Returns |
| 639 |
/// None otherwise. |
| 640 |
/// |
| 641 |
/// ``` |
| 642 |
/// # use serde_json::json; |
| 643 |
/// # |
| 644 |
/// let v = json!({ "a": 64, "b": -64, "c": 256.0 }); |
| 645 |
/// |
| 646 |
/// assert_eq!(v["a"].as_u64(), Some(64)); |
| 647 |
/// assert_eq!(v["b"].as_u64(), None); |
| 648 |
/// assert_eq!(v["c"].as_u64(), None); |
| 649 |
/// ``` |
| 650 |
pub fn as_u64(&self) -> Option<u64> { |
| 651 |
match self { |
| 652 |
Value::Number(n) => n.as_u64(), |
| 653 |
_ => None, |
| 654 |
} |
| 655 |
} |
| 656 |
|
| 657 |
/// If the `Value` is a number, represent it as f64 if possible. Returns |
| 658 |
/// None otherwise. |
| 659 |
/// |
| 660 |
/// ``` |
| 661 |
/// # use serde_json::json; |
| 662 |
/// # |
| 663 |
/// let v = json!({ "a": 256.0, "b": 64, "c": -64 }); |
| 664 |
/// |
| 665 |
/// assert_eq!(v["a"].as_f64(), Some(256.0)); |
| 666 |
/// assert_eq!(v["b"].as_f64(), Some(64.0)); |
| 667 |
/// assert_eq!(v["c"].as_f64(), Some(-64.0)); |
| 668 |
/// ``` |
| 669 |
pub fn as_f64(&self) -> Option<f64> { |
| 670 |
match self { |
| 671 |
Value::Number(n) => n.as_f64(), |
| 672 |
_ => None, |
| 673 |
} |
| 674 |
} |
| 675 |
|
| 676 |
/// Returns true if the `Value` is a Boolean. Returns false otherwise. |
| 677 |
/// |
| 678 |
/// For any Value on which `is_boolean` returns true, `as_bool` is |
| 679 |
/// guaranteed to return the boolean value. |
| 680 |
/// |
| 681 |
/// ``` |
| 682 |
/// # use serde_json::json; |
| 683 |
/// # |
| 684 |
/// let v = json!({ "a": false, "b": "false" }); |
| 685 |
/// |
| 686 |
/// assert!(v["a"].is_boolean()); |
| 687 |
/// |
| 688 |
/// // The string `"false"` is a string, not a boolean. |
| 689 |
/// assert!(!v["b"].is_boolean()); |
| 690 |
/// ``` |
| 691 |
pub fn is_boolean(&self) -> bool { |
| 692 |
self.as_bool().is_some() |
| 693 |
} |
| 694 |
|
| 695 |
/// If the `Value` is a Boolean, returns the associated bool. Returns None |
| 696 |
/// otherwise. |
| 697 |
/// |
| 698 |
/// ``` |
| 699 |
/// # use serde_json::json; |
| 700 |
/// # |
| 701 |
/// let v = json!({ "a": false, "b": "false" }); |
| 702 |
/// |
| 703 |
/// assert_eq!(v["a"].as_bool(), Some(false)); |
| 704 |
/// |
| 705 |
/// // The string `"false"` is a string, not a boolean. |
| 706 |
/// assert_eq!(v["b"].as_bool(), None); |
| 707 |
/// ``` |
| 708 |
pub fn as_bool(&self) -> Option<bool> { |
| 709 |
match *self { |
| 710 |
Value::Bool(b) => Some(b), |
| 711 |
_ => None, |
| 712 |
} |
| 713 |
} |
| 714 |
|
| 715 |
/// Returns true if the `Value` is a Null. Returns false otherwise. |
| 716 |
/// |
| 717 |
/// For any Value on which `is_null` returns true, `as_null` is guaranteed |
| 718 |
/// to return `Some(())`. |
| 719 |
/// |
| 720 |
/// ``` |
| 721 |
/// # use serde_json::json; |
| 722 |
/// # |
| 723 |
/// let v = json!({ "a": null, "b": false }); |
| 724 |
/// |
| 725 |
/// assert!(v["a"].is_null()); |
| 726 |
/// |
| 727 |
/// // The boolean `false` is not null. |
| 728 |
/// assert!(!v["b"].is_null()); |
| 729 |
/// ``` |
| 730 |
pub fn is_null(&self) -> bool { |
| 731 |
self.as_null().is_some() |
| 732 |
} |
| 733 |
|
| 734 |
/// If the `Value` is a Null, returns (). Returns None otherwise. |
| 735 |
/// |
| 736 |
/// ``` |
| 737 |
/// # use serde_json::json; |
| 738 |
/// # |
| 739 |
/// let v = json!({ "a": null, "b": false }); |
| 740 |
/// |
| 741 |
/// assert_eq!(v["a"].as_null(), Some(())); |
| 742 |
/// |
| 743 |
/// // The boolean `false` is not null. |
| 744 |
/// assert_eq!(v["b"].as_null(), None); |
| 745 |
/// ``` |
| 746 |
pub fn as_null(&self) -> Option<()> { |
| 747 |
match *self { |
| 748 |
Value::Null => Some(()), |
| 749 |
_ => None, |
| 750 |
} |
| 751 |
} |
| 752 |
|
| 753 |
/// Looks up a value by a JSON Pointer. |
| 754 |
/// |
| 755 |
/// JSON Pointer defines a string syntax for identifying a specific value |
| 756 |
/// within a JavaScript Object Notation (JSON) document. |
| 757 |
/// |
| 758 |
/// A Pointer is a Unicode string with the reference tokens separated by `/`. |
| 759 |
/// Inside tokens `/` is replaced by `~1` and `~` is replaced by `~0`. The |
| 760 |
/// addressed value is returned and if there is no such value `None` is |
| 761 |
/// returned. |
| 762 |
/// |
| 763 |
/// For more information read [RFC6901](https://tools.ietf.org/html/rfc6901). |
| 764 |
/// |
| 765 |
/// # Examples |
| 766 |
/// |
| 767 |
/// ``` |
| 768 |
/// # use serde_json::json; |
| 769 |
/// # |
| 770 |
/// let data = json!({ |
| 771 |
/// "x": { |
| 772 |
/// "y": ["z", "zz"] |
| 773 |
/// } |
| 774 |
/// }); |
| 775 |
/// |
| 776 |
/// assert_eq!(data.pointer("/x/y/1").unwrap(), &json!("zz")); |
| 777 |
/// assert_eq!(data.pointer("/a/b/c"), None); |
| 778 |
/// ``` |
| 779 |
pub fn pointer(&self, pointer: &str) -> Option<&Value> { |
| 780 |
if pointer.is_empty() { |
| 781 |
return Some(self); |
| 782 |
} |
| 783 |
if !pointer.starts_with('/') { |
| 784 |
return None; |
| 785 |
} |
| 786 |
pointer |
| 787 |
.split('/') |
| 788 |
.skip(1) |
| 789 |
.map(|x| x.replace("~1", "/").replace("~0", "~")) |
| 790 |
.try_fold(self, |target, token| match target { |
| 791 |
Value::Object(map) => map.get(&token), |
| 792 |
Value::Array(list) => parse_index(&token).and_then(|x| list.get(x)), |
| 793 |
_ => None, |
| 794 |
}) |
| 795 |
} |
| 796 |
|
| 797 |
/// Looks up a value by a JSON Pointer and returns a mutable reference to |
| 798 |
/// that value. |
| 799 |
/// |
| 800 |
/// JSON Pointer defines a string syntax for identifying a specific value |
| 801 |
/// within a JavaScript Object Notation (JSON) document. |
| 802 |
/// |
| 803 |
/// A Pointer is a Unicode string with the reference tokens separated by `/`. |
| 804 |
/// Inside tokens `/` is replaced by `~1` and `~` is replaced by `~0`. The |
| 805 |
/// addressed value is returned and if there is no such value `None` is |
| 806 |
/// returned. |
| 807 |
/// |
| 808 |
/// For more information read [RFC6901](https://tools.ietf.org/html/rfc6901). |
| 809 |
/// |
| 810 |
/// # Example of Use |
| 811 |
/// |
| 812 |
/// ``` |
| 813 |
/// use serde_json::Value; |
| 814 |
/// |
| 815 |
/// fn main() { |
| 816 |
/// let s = r#"{"x": 1.0, "y": 2.0}"#; |
| 817 |
/// let mut value: Value = serde_json::from_str(s).unwrap(); |
| 818 |
/// |
| 819 |
/// // Check value using read-only pointer |
| 820 |
/// assert_eq!(value.pointer("/x"), Some(&1.0.into())); |
| 821 |
/// // Change value with direct assignment |
| 822 |
/// *value.pointer_mut("/x").unwrap() = 1.5.into(); |
| 823 |
/// // Check that new value was written |
| 824 |
/// assert_eq!(value.pointer("/x"), Some(&1.5.into())); |
| 825 |
/// // Or change the value only if it exists |
| 826 |
/// value.pointer_mut("/x").map(|v| *v = 1.5.into()); |
| 827 |
/// |
| 828 |
/// // "Steal" ownership of a value. Can replace with any valid Value. |
| 829 |
/// let old_x = value.pointer_mut("/x").map(Value::take).unwrap(); |
| 830 |
/// assert_eq!(old_x, 1.5); |
| 831 |
/// assert_eq!(value.pointer("/x").unwrap(), &Value::Null); |
| 832 |
/// } |
| 833 |
/// ``` |
| 834 |
pub fn pointer_mut(&mut self, pointer: &str) -> Option<&mut Value> { |
| 835 |
if pointer.is_empty() { |
| 836 |
return Some(self); |
| 837 |
} |
| 838 |
if !pointer.starts_with('/') { |
| 839 |
return None; |
| 840 |
} |
| 841 |
pointer |
| 842 |
.split('/') |
| 843 |
.skip(1) |
| 844 |
.map(|x| x.replace("~1", "/").replace("~0", "~")) |
| 845 |
.try_fold(self, |target, token| match target { |
| 846 |
Value::Object(map) => map.get_mut(&token), |
| 847 |
Value::Array(list) => parse_index(&token).and_then(move |x| list.get_mut(x)), |
| 848 |
_ => None, |
| 849 |
}) |
| 850 |
} |
| 851 |
|
| 852 |
/// Takes the value out of the `Value`, leaving a `Null` in its place. |
| 853 |
/// |
| 854 |
/// ``` |
| 855 |
/// # use serde_json::json; |
| 856 |
/// # |
| 857 |
/// let mut v = json!({ "x": "y" }); |
| 858 |
/// assert_eq!(v["x"].take(), json!("y")); |
| 859 |
/// assert_eq!(v, json!({ "x": null })); |
| 860 |
/// ``` |
| 861 |
pub fn take(&mut self) -> Value { |
| 862 |
mem::replace(self, Value::Null) |
| 863 |
} |
| 864 |
} |
| 865 |
|
| 866 |
/// The default value is `Value::Null`. |
| 867 |
/// |
| 868 |
/// This is useful for handling omitted `Value` fields when deserializing. |
| 869 |
/// |
| 870 |
/// # Examples |
| 871 |
/// |
| 872 |
/// ``` |
| 873 |
/// # use serde::Deserialize; |
| 874 |
/// use serde_json::Value; |
| 875 |
/// |
| 876 |
/// #[derive(Deserialize)] |
| 877 |
/// struct Settings { |
| 878 |
/// level: i32, |
| 879 |
/// #[serde(default)] |
| 880 |
/// extras: Value, |
| 881 |
/// } |
| 882 |
/// |
| 883 |
/// # fn try_main() -> Result<(), serde_json::Error> { |
| 884 |
/// let data = r#" { "level": 42 } "#; |
| 885 |
/// let s: Settings = serde_json::from_str(data)?; |
| 886 |
/// |
| 887 |
/// assert_eq!(s.level, 42); |
| 888 |
/// assert_eq!(s.extras, Value::Null); |
| 889 |
/// # |
| 890 |
/// # Ok(()) |
| 891 |
/// # } |
| 892 |
/// # |
| 893 |
/// # try_main().unwrap() |
| 894 |
/// ``` |
| 895 |
impl Default for Value { |
| 896 |
fn default() -> Value { |
| 897 |
Value::Null |
| 898 |
} |
| 899 |
} |
| 900 |
|
| 901 |
mod de; |
| 902 |
mod from; |
| 903 |
mod index; |
| 904 |
mod partial_eq; |
| 905 |
mod ser; |
| 906 |
|
| 907 |
/// Convert a `T` into `serde_json::Value` which is an enum that can represent |
| 908 |
/// any valid JSON data. |
| 909 |
/// |
| 910 |
/// # Example |
| 911 |
/// |
| 912 |
/// ``` |
| 913 |
/// use serde::Serialize; |
| 914 |
/// use serde_json::json; |
| 915 |
/// use std::error::Error; |
| 916 |
/// |
| 917 |
/// #[derive(Serialize)] |
| 918 |
/// struct User { |
| 919 |
/// fingerprint: String, |
| 920 |
/// location: String, |
| 921 |
/// } |
| 922 |
/// |
| 923 |
/// fn compare_json_values() -> Result<(), Box<dyn Error>> { |
| 924 |
/// let u = User { |
| 925 |
/// fingerprint: "0xF9BA143B95FF6D82".to_owned(), |
| 926 |
/// location: "Menlo Park, CA".to_owned(), |
| 927 |
/// }; |
| 928 |
/// |
| 929 |
/// // The type of `expected` is `serde_json::Value` |
| 930 |
/// let expected = json!({ |
| 931 |
/// "fingerprint": "0xF9BA143B95FF6D82", |
| 932 |
/// "location": "Menlo Park, CA", |
| 933 |
/// }); |
| 934 |
/// |
| 935 |
/// let v = serde_json::to_value(u).unwrap(); |
| 936 |
/// assert_eq!(v, expected); |
| 937 |
/// |
| 938 |
/// Ok(()) |
| 939 |
/// } |
| 940 |
/// # |
| 941 |
/// # compare_json_values().unwrap(); |
| 942 |
/// ``` |
| 943 |
/// |
| 944 |
/// # Errors |
| 945 |
/// |
| 946 |
/// This conversion can fail if `T`'s implementation of `Serialize` decides to |
| 947 |
/// fail, or if `T` contains a map with non-string keys. |
| 948 |
/// |
| 949 |
/// ``` |
| 950 |
/// use std::collections::BTreeMap; |
| 951 |
/// |
| 952 |
/// fn main() { |
| 953 |
/// // The keys in this map are vectors, not strings. |
| 954 |
/// let mut map = BTreeMap::new(); |
| 955 |
/// map.insert(vec![32, 64], "x86"); |
| 956 |
/// |
| 957 |
/// println!("{}", serde_json::to_value(map).unwrap_err()); |
| 958 |
/// } |
| 959 |
/// ``` |
| 960 |
// Taking by value is more friendly to iterator adapters, option and result |
| 961 |
// consumers, etc. See https://github.com/serde-rs/json/pull/149. |
| 962 |
pub fn to_value<T>(value: T) -> Result<Value, Error> |
| 963 |
where |
| 964 |
T: Serialize, |
| 965 |
{ |
| 966 |
value.serialize(Serializer) |
| 967 |
} |
| 968 |
|
| 969 |
/// Interpret a `serde_json::Value` as an instance of type `T`. |
| 970 |
/// |
| 971 |
/// # Example |
| 972 |
/// |
| 973 |
/// ``` |
| 974 |
/// use serde::Deserialize; |
| 975 |
/// use serde_json::json; |
| 976 |
/// |
| 977 |
/// #[derive(Deserialize, Debug)] |
| 978 |
/// struct User { |
| 979 |
/// fingerprint: String, |
| 980 |
/// location: String, |
| 981 |
/// } |
| 982 |
/// |
| 983 |
/// fn main() { |
| 984 |
/// // The type of `j` is `serde_json::Value` |
| 985 |
/// let j = json!({ |
| 986 |
/// "fingerprint": "0xF9BA143B95FF6D82", |
| 987 |
/// "location": "Menlo Park, CA" |
| 988 |
/// }); |
| 989 |
/// |
| 990 |
/// let u: User = serde_json::from_value(j).unwrap(); |
| 991 |
/// println!("{:#?}", u); |
| 992 |
/// } |
| 993 |
/// ``` |
| 994 |
/// |
| 995 |
/// # Errors |
| 996 |
/// |
| 997 |
/// This conversion can fail if the structure of the Value does not match the |
| 998 |
/// structure expected by `T`, for example if `T` is a struct type but the Value |
| 999 |
/// contains something other than a JSON map. It can also fail if the structure |
| 1000 |
/// is correct but `T`'s implementation of `Deserialize` decides that something |
| 1001 |
/// is wrong with the data, for example required struct fields are missing from |
| 1002 |
/// the JSON map or some number is too big to fit in the expected primitive |
| 1003 |
/// type. |
| 1004 |
pub fn from_value<T>(value: Value) -> Result<T, Error> |
| 1005 |
where |
| 1006 |
T: DeserializeOwned, |
| 1007 |
{ |
| 1008 |
T::deserialize(value) |
| 1009 |
} |