简体   繁体   English

使用python转换JSON对象数组

[英]Convert array of JSON objects using python

I have the following function in python, which is a query: 我在python中有以下函数,这是一个查询:

The output of this is a table. 此输出是一个表。

def queryNoScan(start_time_prod,date_object,start_time_scan,date_object_scan):
    query_basictable = """
    SELECT t1.Machine, t1.Production, t2.Scanned, (t1.Production-t2.Scanned) as Delta
        FROM
         (SELECT MCH_CODE as Machine, COUNT(CODE) AS Production
                FROM table1
                        WHERE CODE = 'PROD' AND SUBCODE = 'MACH'  
                        AND EVS_START  between '%s'and '%s' and PP_CODE ='A'
                        GROUP BY MCH_CODE) t1 
        INNER JOIN
         (SELECT MCH_CODE as Machine,  COUNT(BARCODE) AS Scanned
                FROM table2
                        WHERE TRC_TIMESTAMP between '%s'and '%s' AND PP_CODE ='A'
                        GROUP BY MCH_CODE) t2 ON t1.Machine=t2.Machine
                        ORDER BY Delta desc
    """ %(start_time_prod,date_object,start_time_scan,date_object_scan)

    scan_data = pd.read_sql(sql=query_basictable, con=engine)

    return scan_data

How can I convert the output of this function to a JSON of strings which I will passed them later in a front end. 如何将此函数的输出转换为字符串的JSON,稍后将在前端将它们传递给我。 Like: "machine": {"Machine2": 14317, etc etc 如:“机器”:{“机器2”:14317,依此类推

You can use the to_json method from pandas to convert your dataframe into a json string. 您可以使用pandas中的to_json方法将数据to_json转换为json字符串。 In the documentation you can also find some helpful examples. 在文档中,您还可以找到一些有用的示例。

And please don't ignore the comment from chepner since he's right. 而且请不要忽略chepner的评论,因为他是对的。 You should not use the string formatting operation to generate SQL queries. 您不应使用字符串格式化操作来生成SQL查询。

Instead use the params argument of the read_sql method: 而是使用read_sql方法的params参数:

def queryNoScan(start_time_prod, date_object, start_time_scan, date_object_scan):
    query_basictable = """
    SELECT t1.Machine, t1.Production, t2.Scanned, (t1.Production-t2.Scanned) as Delta
        FROM
         (SELECT MCH_CODE as Machine, COUNT(CODE) AS Production
                FROM table1
                        WHERE CODE = 'PROD' AND SUBCODE = 'MACH'  
                        AND EVS_START  between %s and %s and PP_CODE ='A'
                        GROUP BY MCH_CODE) t1 
        INNER JOIN
         (SELECT MCH_CODE as Machine,  COUNT(BARCODE) AS Scanned
                FROM table2
                        WHERE TRC_TIMESTAMP between %s and %s AND PP_CODE ='A'
                        GROUP BY MCH_CODE) t2 ON t1.Machine=t2.Machine
                        ORDER BY Delta desc
    """ 
    params = (start_time_prod, date_object, start_time_scan, date_object_scan)

    scan_data = pd.read_sql(sql=query_basictable, con=engine, params=params)

    return scan_data.to_json()

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

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