Loop through JSON object in mysql function

前端 未结 1 1995
灰色年华
灰色年华 2021-01-11 21:12

I have a json object which has list of products under a bill. I want to write a mysql function for it which reads the data from the json and iterates over it one by one and

相关标签:
1条回答
  • 2021-01-11 21:51

    You can use a WHILE loop in conjunction with JSON_LENGTH to achieve this:

    DECLARE json, products, product VARCHAR(4000);
    DECLARE i INT DEFAULT 0;
    SELECT '{"billNo":16,"date":"2017-13-11 09:05:01","customerName":"Vikas","total":350.0,"fixedCharges":100,"taxAmount":25.78,"status":"paid","product":[{"productId":"MRR11","categoryId":72,"categoryName":"Parker Pen","cost":200,"quantity":2,"log":{"supplierId":"725","supplierName":"Rihant General Stores"}},{"productId":"MRR12","categoryId":56,"categoryName":"Drawing Books","cost":150,"quantity":3,"log":{"supplierId":"725","supplierName":"Rihant General Stores"}}]}
    ' INTO json;
    
    SELECT json->"$.product" INTO products;
    
    WHILE i < JSON_LENGTH(products) DO
        SELECT JSON_EXTRACT(products,CONCAT('$[',i,']')) INTO product;
        SELECT product;
        SELECT i + 1 INTO i;
    END WHILE;
    

    You'll probably need to do more than simply 'SELECT product' though ;-)

    NOTE: MySQL JSON functions were added in 5.7.8 so you'll need to check your MySQL version first.

    0 讨论(0)
提交回复
热议问题