无法访问嵌套 json 数组中的数据

Can't get access to data from nested json's array

如何从 employment_types (type, salary) 和 skills (name, level) 数组中检索值并显示他们在列?我试过 employment_types 更不用说 skills:

declare @json nvarchar(max)
set @json = '[
  {
    "title": "IT Admin",
    "experience_level": "mid",
    "employment_types": [
      {
        "type": "permanent",
        "salary": null
      }
    ],
    "skills": [
      {
        "name": "Security",
        "level": 3
      },
      {
        "name": "WIFI",
        "level": 3
      },
      {
        "name": "switching",
        "level": 3
      }
    ]
  },
  {
    "title": "Lead QA Engineer",
    "experience_level": "mid",
    "employment_types": [
      {
        "type": "permanent",
        "salary": {
          "from": 7000,
          "to": 13000,
          "currency": "pln"
        }
      }
    ],
    "skills": [
      {
        "name": "Embedded C",
        "level": 4
      },
      {
        "name": "Quality Assurance",
        "level": 4
      },
      {
        "name": "C++",
        "level": 4
      }
    ]
  }
]';


SELECT *
FROM OPENJSON(@JSON, '$.employment_types')
WITH
(
    type nvarchar(50) '$.type',
    salary varchar(max) '$.salary'

)

有将近 7000 条记录,我想显示所有这些记录中提到的上述列。

很难确切地知道您想要什么,因为 employment_typesskills 都是数组。但是假设 employment_types 总是只有一个元素,你可以这样做

SELECT
  j1.title,
  j1.experience_level,
  j1.employment_type,
  salary = j1.salary_currency + ' ' + CONCAT(j1.salary_from, ' - ', j1.salary_to),
  j2.name,
  j2.level
FROM OPENJSON(@JSON)
  WITH (
    title nvarchar(100),
    experience_level nvarchar(10),
    employment_type nvarchar(50) '$.employment_types[0].type',
    salary_from int '$.employment_types[0].salary.from',
    salary_to int '$.employment_types[0].salary.to',
    salary_currency char(3) '$.employment_types[0].salary.currency',
    skills nvarchar(max) AS JSON
  ) j1
CROSS APPLY OPENJSON(j1.skills)
WITH
(
    name nvarchar(50),
    level int
) j2

db<>fiddle

  • 由于我们直接从根对象中提取数据,因此不需要 JSON 路径参数。 OPENJSON 会自动将数组分成单独的行。如果你只是想要 employment_types,你可以直接使用路径参数。
  • employment_types[0]表示只获取数组的第一个元素。如果你想要所有的元素,你将需要另一个 OPENJSON
  • 注意 skills 使用 AS JSON,这意味着整个 JSON 数组被拉出,然后可以通过对 OPENJSON 的另一个调用来推送