Skip to content

Commit 0775592

Browse files
authored
Add documentation examples for members and entries (#182)
1 parent 752f942 commit 0775592

File tree

1 file changed

+34
-0
lines changed

1 file changed

+34
-0
lines changed

src/value/mod.rs

Lines changed: 34 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -435,6 +435,19 @@ impl JsonValue {
435435

436436
/// Works on `JsonValue::Array` - returns an iterator over members.
437437
/// Will return an empty iterator if called on non-array types.
438+
/// ## Example
439+
/// ```
440+
/// # use json::JsonValue;
441+
/// # #[macro_use] use json::array;
442+
/// let animals = array!["Cat", "Dog", "Snail"];
443+
/// let mut animals_with_letter_a = Vec::new();
444+
/// for animal in animals.members() {
445+
/// if animal.as_str().unwrap().contains('a') {
446+
/// animals_with_letter_a.push(animal);
447+
/// }
448+
/// }
449+
/// assert_eq!(animals_with_letter_a, vec!["Cat", "Snail"]);
450+
/// ```
438451
pub fn members(&self) -> Members {
439452
match *self {
440453
JsonValue::Array(ref vec) => {
@@ -457,6 +470,27 @@ impl JsonValue {
457470

458471
/// Works on `JsonValue::Object` - returns an iterator over key value pairs.
459472
/// Will return an empty iterator if called on non-object types.
473+
/// ## Example
474+
/// ```
475+
/// # use json::JsonValue;
476+
/// let heights = json::parse(r#"
477+
/// {
478+
/// "Alice": 1.42,
479+
/// "Bob": 1.6,
480+
/// "Carlos": 2.1
481+
/// }
482+
/// "#).unwrap();
483+
/// let mut total_height = 0.0;
484+
/// let mut names_with_o: Vec<&str> = Vec::new();
485+
/// for (name, height) in heights.entries() {
486+
/// total_height += height.as_f64().unwrap();
487+
/// if name.contains('o') {
488+
/// names_with_o.push(name);
489+
/// }
490+
/// }
491+
/// assert_eq!(total_height, 5.12);
492+
/// assert_eq!(names_with_o, vec!["Bob", "Carlos"]);
493+
/// ```
460494
pub fn entries(&self) -> Entries {
461495
match *self {
462496
JsonValue::Object(ref object) => {

0 commit comments

Comments
 (0)