55// It can be operated on (e.g. INCR) and serialized back to JSON.
66
77use serde_json:: Value ;
8- use jsonpath:: Selector ;
8+ use jsonpath_lib as jsonpath;
99
1010pub struct Error {
1111 msg : String ,
1212}
1313
14+ impl From < String > for Error {
15+ fn from ( e : String ) -> Self {
16+ Error { msg : e }
17+ }
18+ }
19+
1420impl From < serde_json:: Error > for Error {
1521 fn from ( e : serde_json:: Error ) -> Self {
16- Error { msg : format ! ( "{}" , e. to_string( ) ) }
22+ Error { msg : e. to_string ( ) }
1723 }
1824}
1925
@@ -52,49 +58,31 @@ impl RedisJSON {
5258 pub fn to_string ( & self , path : & str ) -> Result < String , Error > {
5359 eprintln ! ( "Serializing back to JSON" ) ;
5460
55- let s = match self . get_doc ( path) ? {
56- Some ( doc) => serde_json:: to_string ( & doc) ?,
57- None => String :: new ( )
58- } ;
59-
60- Ok ( s)
61+ let results = self . get_doc ( path) ?;
62+ Ok ( serde_json:: to_string ( & results) ?)
6163 }
6264
6365 pub fn str_len ( & self , path : & str ) -> Result < usize , Error > {
64- match self . get_doc ( path) ? {
65- Some ( doc) => {
66- match doc. as_str ( ) {
67- Some ( s) => Ok ( s. len ( ) ) ,
68- None => Err ( Error { msg : "ERR wrong type of path value" . to_string ( ) } )
69- }
70- }
71- None => Ok ( 0 ) // path not found
66+ match self . get_doc ( path) ?. as_str ( ) {
67+ Some ( s) => Ok ( s. len ( ) ) ,
68+ None => Err ( Error { msg : "ERR wrong type of path value" . to_string ( ) } )
7269 }
7370 }
7471
7572 pub fn get_type ( & self , path : & str ) -> Result < String , Error > {
7673 let s = match self . get_doc ( path) ? {
77- Some ( doc) => {
78- match doc {
79- Value :: Null => "null" ,
80- Value :: Bool ( _) => "boolean" ,
81- Value :: Number ( _) => "number" ,
82- Value :: String ( _) => "string" ,
83- Value :: Array ( _) => "array" ,
84- Value :: Object ( _) => "object" ,
85- }
86- }
87- None => ""
74+ Value :: Null => "null" ,
75+ Value :: Bool ( _) => "boolean" ,
76+ Value :: Number ( _) => "number" ,
77+ Value :: String ( _) => "string" ,
78+ Value :: Array ( _) => "array" ,
79+ Value :: Object ( _) => "object" ,
8880 } ;
8981 Ok ( s. to_string ( ) )
9082 }
9183
92- pub fn get_doc ( & self , path : & str ) -> Result < Option < & Value > , Error > {
93- // Create a JSONPath selector
94- let selector = Selector :: new ( path) . map_err ( |e| Error {
95- msg : format ! ( "{}" , e) ,
96- } ) ?;
97-
98- Ok ( selector. find ( & self . data ) . next ( ) )
84+ pub fn get_doc ( & self , path : & str ) -> Result < Value , Error > {
85+ let results = jsonpath:: select ( & self . data , path) ?;
86+ Ok ( results)
9987 }
10088}
0 commit comments