ceph_async/json.rs
1// Copyright 2017 LambdaStack All rights reserved.
2//
3// Licensed under the Apache License, Version 2.0 (the "License");
4// you may not use this file except in compliance with the License.
5// You may obtain a copy of the License at
6//
7// http://www.apache.org/licenses/LICENSE-2.0
8//
9// Unless required by applicable law or agreed to in writing, software
10// distributed under the License is distributed on an "AS IS" BASIS,
11// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12// See the License for the specific language governing permissions and
13// limitations under the License.
14
15use std::str;
16
17use serde_json;
18
19use crate::JsonData;
20// use JsonValue;
21
22/// First json call that takes a JSON formatted string and converts it to
23/// JsonData object that can then be traversed using `json_find` via the key
24/// path.
25pub fn json_data(json_str: &str) -> Option<JsonData> {
26 match serde_json::from_str(json_str) {
27 Ok(json_data) => Some(json_data),
28 Err(_) => None,
29 }
30}
31
32/// Looks for the parent object first and then the 'child' object. If the
33/// parent object is None then it only looks for the 'child' object. The parent
34/// object is used for situations where there may be 'child' objects with the
35/// same name.
36pub fn json_find(json_data: JsonData, keys: &[&str]) -> Option<JsonData> {
37 let mut value = json_data;
38 for key in keys {
39 match value.get(key) {
40 Some(v) => value = v.clone(),
41 None => return None,
42 }
43 }
44
45 Some(value)
46}
47
48/// More specific String cast of an individual JsonData object.
49pub fn json_as_string(json_data: &JsonData) -> String {
50 json_data.to_string()
51}