简体   繁体   中英

How to parse JSON array to SQL Table

I'm stuck with some problem. I have no idea how to read all nodes in JSON objects list.

I have 3 items (objects) with headers [item1, item2, item3] .

I need to get name of the item and all inner fields, like this: table screenshot

Here is source JSON data:

{
  "item1": {
    "title": "2",
    "value": null,
    "visible": true,
    "name": "item1",
    "enabled": true,
    "readonly": false,
    "id": "f1f46ce6-9d0b-4eaf-88b7-d35b23a4d2e4"
  },
  "item2": {
    "title": null,
    "value": null
    "visible": true,
    "name": "item2",
    "enabled": true,
    "readonly": false,
    "id": "da2b8a02-cfbd-4de8-8a33-74e2a484475a"
  },
  "item3": {
    "title": "",
    "value": null,
    "visible": true,
    "name": "item3",
    "enabled": true,
    "readonly": false,
    "id": "57ee45d6-41d7-45c2-b022-13220e31d2d2"
  }
}

I found approach how to do it with OPENJSON() or JSON_VALUE() functions, but I still can't iterate over all items..

  SELECT * FROM OPENJSON (@json, '$.item1')
    WITH (
        ItemName VARCHAR(100) '$',
        Title VARCHAR(100) '$.name',
        Value VARCHAR(100) '$.value',
        Visible VARCHAR(100) '$.visible',
        Name VARCHAR(100) '$.name',
        Enabled VARCHAR(100) '$.enabled',
        ReadOnly VARCHAR(100) '$.readonly',
        Id VARCHAR(500) '$.id'
    )

Something like this?

SELECT [Key].[key] AS [ItemName], [Value].*
FROM OPENJSON (@json, '$') AS [Key]
CROSS APPLY OPENJSON([Key].value)
    WITH (
        Title VARCHAR(100) '$.title',
        Value VARCHAR(100) '$.value',
        Visible VARCHAR(100) '$.visible',
        Name VARCHAR(100) '$.name',
        Enabled VARCHAR(100) '$.enabled',
        ReadOnly VARCHAR(100) '$.readonly',
        Id VARCHAR(500) '$.id'
    ) AS [Value]

The "trick" is the cross apply on the sub-objects json graph.

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