简体   繁体   中英

How to extract nested json?

I have a table name 'my doc'. And there is a column which is a nested json called 'element'. The structure is as below.

I wanna extract the element_id as a column. How to make it with sql? Thanks

{
   “element”: {
     “1”: {
          “element_id”:”3jakd4ks”,
          “type”: “square”,
          “name”: “eggplant”
           },
      
      “2”: {
          “element_id”:” ieh3iusk”;
          “type”: “circle”,
          “name”: “orange”
           },

      “3”: {
          “element_id”:”766wjdhh”;
          “type”: “circle”,
          “name”: “apple”
           }
      }
}

If you are working with SQL Server, and your data is stored in a table, the syntax would be something like this. Your schema may be different, but refer to Microsoft documentation for more details. https://docs.microsoft.com/en-us/sql/relational-databases/json/json-data-sql-server?view=sql-server-ver15

SELECT  v.*
FROM    Table1 AS t
        CROSS APPLY
        OPENJSON(t.JSONColumn)
        WITH (
                 ResultID NVARCHAR(MAX) '$.element' AS JSON
             ) AS Returned
        CROSS APPLY (
                        SELECT  element_id
                                ,type
                                ,name
                        FROM
                                OPENJSON(Returned.ResultID)
                                WITH (
                                         element_id VARCHAR(MAX) '$.element_id'
                                         ,type VARCHAR(MAX) '$.type'
                                         ,name VARCHAR(MAX) '$.name'
                                     )
                    ) AS v;

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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