mySQL下json数组/多行数据的遍历

本文介绍了如何在MySQL中利用JSON_EXTRACT函数和存储过程遍历JSON数组,并将数据插入到数据库表中。通过示例展示了在处理过程中需要注意的字符串与变量的转换,以及如何避免常见的错误。内容包括使用CONCAT函数和WHILE循环来正确访问和操作JSON对象的各个元素。
摘要由CSDN通过智能技术生成

              在处理json串时我们经常遇到json里的数组,我们访问json数组可以使用mySQL的JSON_EXTRACT(jsonstr,"$[0].key")函数得到key的值;但是由于JSON_EXTRACT的第二参数$[0]是字符串,在存储过程或函数中遍历json数据时很容易犯得错误是直接将变量整数i写为JSON_EXTRACT(jsonstr,"$[i].key")形式这时根本无得到key的值,因为JSON_EXTRACT认为i也是字符串而非变量,这时就需要使用如下的写法就能正确的完成遍历JSON_EXTRACT(jsonstr,CONCAT('$[',CONVERT(i,CHAR),'].key')),这样我们无论是用FOR 或WHILE 都可以方便的遍历Json串中的多行数据。以下是一个遍历json数组的存储过程。

 WHILE i<m DO
          SET  ic=CONVERT(i,CHAR);#concat('$[',ic,'].probability')
           INSERT INTO `custom_data_1066_invoicedetails` 
                        SET dguid= REPLACE(JSON_EXTRACT(JSON_EXTRACT(mdetails,"$.details"),CONCAT('$[',ic,'].guid')),'"',''),
                            invoicecodeconfirm= REPLACE(JSON_EXTRACT(JSON_EXTRACT(mdetails,"$.details"),CONCAT('$[',ic,'].InvoiceCodeConfirm')),'"',''),
                            invoicenum= REPLACE(JSON_EXTRACT(JSON_EXTRACT(mdetails,"$.details"),CONCAT('$[',ic,'].InvoiceNum')),'"',''),
                            InvoiceType= REPLACE(JSON_EXTRACT(JSON_EXTRACT(mdetails,"$.details"),CONCAT('$[',ic,'].InvoiceType')),'"',''),
                            VatType= REPLACE(JSON_EXTRACT(JSON_EXTRACT(mdetails,"$.details"),CONCAT('$[',ic,'].VatType')),'"',''),
                            InvoiceDate= REPLACE(JSON_EXTRACT(JSON_EXTRACT(mdetails,"$.details"),CONCAT('$[',ic,'].InvoiceDate')),'"',''),
                            InvoiceTypeOrg= REPLACE(JSON_EXTRACT(JSON_EXTRACT(mdetails,"$.details"),CONCAT('$[',ic,'].InvoiceTypeOrg')),'"',''),
                            AmountInFiguers= REPLACE(JSON_EXTRACT(JSON_EXTRACT(mdetails,"$.details"),CONCAT('$[',ic,'].AmountInFiguers')),'"',''),
                            TotalTax= REPLACE(JSON_EXTRACT(JSON_EXTRACT(mdetails,"$.details"),CONCAT('$[',ic,'].TotalTax')),'"',''), 
                            TotalAmount= REPLACE(JSON_EXTRACT(JSON_EXTRACT(mdetails,"$.details"),CONCAT('$[',ic,'].TotalAmount')),'"',''),  
                            dCommodityName= REPLACE(JSON_EXTRACT(JSON_EXTRACT(mdetails,"$.details"),CONCAT('$[',ic,'].CommodityName')),'"',''),
                            TaxRate= REPLACE(JSON_EXTRACT(JSON_EXTRACT(mdetails,"$.details"),CONCAT('$[',ic,'].TaxRate')),'"',''),
                            probability= REPLACE(JSON_EXTRACT(JSON_EXTRACT(mdetails,"$.details"),CONCAT('$[',ic,'].probability')),'"',''),
                            created_at=CURRENT_TIMESTAMP(),
                            data_id=tmp;
                    SET i=i+1;
         END WHILE; 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值