使用SQL Server中的OPENJSON来解析非数组对象。

huangapple go评论65阅读模式
英文:

Using OPENJSON in SQL Server to parse a Non-Array Object

问题

我正在使用SQL Server v15,从.NET应用程序调用。

我使用的网站(不是我的 - 我不控制数据)有一个格式奇特的JSON数据集。它不是一个数组,而是一个对象,每个元素都以其ID命名:

{ "1": { "id": "1", "Name": "Charlie" }, "2": { "id": "2", "Name": "Sally" } }

我知道如何使用OPENJSON从数组中读取数据,但是否可能解析这种格式?或者最好的方法是编写一个脚本逐个遍历对象?

英文:

I'm using SQL Server v15, called from a .NET application.

A website I'm using (not mine - I don't control the data) has a JSON dataset formatted strangely. Instead of being an array like:

[{"id":"1","Name":"Charlie"},{"id":"2","Name"="Sally"}]

It's an object with each element named as its ID:

{"1":{"id":"1","Name":"Charlie"}, "2":{"id":"2","Name"="Sally"}}

I know how to use the OPENJSON to read data from an array, but is it possible to have it parse this format? Or is my best bet to have a script loop through the objects one at a time?

答案1

得分: 1

请尝试以下解决方案。

SQL

DECLARE @json NVARCHAR(MAX) = 
N'{
    "1": {
        "id": "1",
        "Name": "Charlie"
    },
    "2": {
        "id": "2",
        "Name": "Sally"
    }
}';

SELECT rs.*
FROM OPENJSON (@json) AS seq
CROSS APPLY OPENJSON(seq.value)
WITH 
(
   [id]		INT			'$.id',
   [Name] VARCHAR(20)	'$.Name'
) AS rs;

Output

id Name
1 Charlie
2 Sally
英文:

Please try the following solution.

SQL

DECLARE @json NVARCHAR(MAX) = 
N'{
	"1": {
		"id": "1",
		"Name": "Charlie"
	},
	"2": {
		"id": "2",
		"Name": "Sally"
	}
}';

SELECT rs.*
FROM OPENJSON (@json) AS seq
CROSS APPLY OPENJSON(seq.value)
WITH 
(
   [id]		INT			'$.id'
   , [Name] VARCHAR(20)	'$.Name'
) AS rs;

Output

id Name
1 Charlie
2 Sally

huangapple
  • 本文由 发表于 2023年2月19日 08:58:06
  • 转载请务必保留本文链接:https://go.coder-hub.com/75497356.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定