1

I wonder if there exists some library to parse a JSON that contains logical operators to transform it into a flat query string.

Let's say as input I get:

{
    "Children":[
       {
          "ID":1,
       },
       {
          "ID":2,
       },
       {
          "Children":[
             {
                "ID":3,
             },
             {
                "ID":4,
             }
          ],
          "Type":"Or"
       }
    ],
    "Type":"And"
 }

And I want to convert it into simply:

(3 Or 4) AND 1 And 2

How would you do this in Python?

1
  • 1
    How did the all caps AND get in there? Commented Aug 26, 2020 at 21:24

1 Answer 1

2

It depends on what your precise expectations are; in particular, this problem is a lot easier if you're OK with redundant parentheses.

Here's a simple recursive function with inadequate error checking (i.e. it's likely to raise an exception if the JSON doesn't precisely conform to expectations):

def json_to_formula(j):
    if 'Children' in j:                                                                
        return '(' + f" {j['Type']} ".join(map(json_to_formula,
                                           j['Children'])) + ')'
    else:
        return str(j['ID'])
Sign up to request clarification or add additional context in comments.

6 Comments

Thx, but what is f in the statement?
@hanshupe: A copy and paste error. Sorry. At the last minute, I thought that f wasn't a very good name for the function, but I copied the old function body instead of the fixed one.
there still one f :)
@HansHupe: f"..." is a Python 3 formatted string literal ("f-string")
@HansHupe: Cool. But remember that it is only a rough guide :-). You'll need to adapt it as you add operator types. (For example, using join works fine for operators like And and Or, but it's not correct for unary operators like Not.)
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.