How can I get the nested keys of a map in clojure?

后端 未结 11 1168
梦如初夏
梦如初夏 2020-12-15 10:59

if my structure is

{ :a :A
  :b :B
  :c {
       :d :D
     }
  :e {
       :f {
            :g :G
            :h :H
          }
     }
}

I

11条回答
  •  被撕碎了的回忆
    2020-12-15 11:19

    You can build this with clojure.zip or tree-seq fairly easily though I strongly prefer the prismatic.schema library for verifying the structure of nested maps

    user> (def my-data-format                                 
      {:a Keyword                                             
       :b Keyword                                             
       :c {:d Keyword}                                        
       :e {:f {:g Keyword                                     
               :h Keyword}}})                                 
    #'user/my-data-format                                     
    user> (def some-data                                      
             {:a :A                                            
              :b :B                                            
              :c {:d :D}                                       
              :e {:f {:g :G                                    
                      :h :G}}})                                
    #'user/some-data                                          
    user> (schema/validate my-data-format some-data)          
    {:a :A, :c {:d :D}, :b :B, :e {:f {:g :G, :h :G}}}
    user> (def some-wrong-data
            {:a :A
             :b :B
             :c {:wrong :D}
             :e {:f {:g :G
                     :h :G}}})
     #'user/some-wrong-data             
    
     user> (schema/validate my-data-format some-wrong-data)  
    
    ExceptionInfo Value does not match schema: 
    {:c {:d missing-required-key, 
         :wrong disallowed-key}}  
    schema.core/validate (core.clj:132)
    

提交回复
热议问题