简体   繁体   English

在 Python 中解析逻辑 JSON 数据

[英]Parse logical JSON data in Python

I wonder if there exists some library to parse a JSON that contains logical operators to transform it into a flat query string.我想知道是否存在一些库来解析包含逻辑运算符的 JSON,以将其转换为平面查询字符串。

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?你会如何在 Python 中做到这一点?

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 (ie it's likely to raise an exception if the JSON doesn't precisely conform to expectations):这是一个简单的递归函数,错误检查不充分(即,如果 JSON 不完全符合预期,则可能会引发异常):

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'])

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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