简体   繁体   中英

How to generate a logical string in python from nested json elements

I have the below nested json structure where I wanted to derived an logical expression based on the structure.

{
   "Name":"Main_Rules",
   "Rules":[
      {
         "logic":"A1",
         "or":[
            {
               "logic":"B",                  
               "or":[
                  {
                     "logic":"C1",                        
                     "or":[
                        {
                           "logic":"D",                               
                           "or":[
                              {
                                 "logic":"E",                                     
                                 "or":[]
                              }
                           ]
                        }
                     ]
                  }
               ]
            },
            {
               "logic":"F",
               "or":[
                  
               ]
            }
         ]
      },
      {
         "logic":"G1",
         "or":[]
      }
   ]
}

The expected string out of the above json is (( A1 OR ( ( B OR (C1 OR D OR E)) AND F )) AND G1 )

(
 ( A1 
    OR 
      ( 
        ( 
          B OR  (C1 OR D OR E)
        )
        AND F
      )
 )
 AND G1
)

Following is how the result string is derived.

A1 is OR condition to result of ( B OR (C1 OR D OR E)) AND F )

B is OR condition to result of (C1 OR D OR E) and the result of (B OR (C1 OR D OR E)) is in AND condition to F

The result of ( A OR ( ( B OR (C OR D OR E)) AND F )) is in AND condition to final G1

If there is no OR condition within A1 then the expected logical string should be (A1 AND G1)

So far I tried string split and iterating the characters, however I couldn't achieve the expected result.

Thanks in advance.

Check this out: https://github.com/nadirizr/json-logic-py

You can edit the code to suit your file structure or use their structure.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM