如何使用SQL选择JSON对象键值
我的数据库中的一些记录在一个名为“ Swatch”的列中,这是描述颜色色板的JSON。每个记录看起来像这样:
{"colors":{"color-1":"transparent","color-2":"transparent"}}
基本上是一个具有许多钥匙值对的大色对象。我想使用SQL操纵此JSON,以实现类似的东西,以允许可自定义的颜色名称。
{"colors":[{"name": "Red", "color":"#00000"},{"name": "Green", "color":"#00000"}]
(十六进制代码仅用于演示,我知道它们不合法)。
我该如何实现?可以使用SQL Server吗?
I have some records in my database in a column called Swatch, that are JSON to describe a colour swatch. Each record looks something like this:
{"colors":{"color-1":"transparent","color-2":"transparent"}}
Basically it's one big colour object with lots of key value pairs. I would like to manipulate this JSON, using SQL, to achieve something like this instead to allow customisable colour names.
{"colors":[{"name": "Red", "color":"#00000"},{"name": "Green", "color":"#00000"}]
(Hex codes are just for demo purposes, I know they're not legit).
How can I achieve this? It is possible using SQL Server?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
可能是可能的,但是很大程度上取决于数据以及您要实现的目标。
有一组 JSON功能可用,其中大多数在SQL 2016中添加,并且SQL中应提供更多功能服务器2022。
如果您想删除当前的结构和数据,以支持一个简单的新结构。
如果您想将当前结构转换为另一种结构,那可能很难,但这与数据相关。
让我们将您的样本视为您要转换的实际数据
是问题和复杂性,我知道
color-1
是什么?它有什么名字?那是人类操作,除非您有一些颜色代码颜色表,否则color-n
键?要清洁属性价值,您需要明确参考它们。 (但是我确定您可以找到其他方法...而无需使用JSON函数)JSON函数示例
我已经播放了JSON数据并创建了一些示例查询,我希望尝试它们会帮助您了解操纵JSON数据的含义,并选择SQL Server是否为适合您的合适工具 任务
It may be possible, but a lot depends on the data and what you are trying to achieve.
There is a set of JSON functions available, most of them added in SQL 2016, and a pair more should be available in SQL Server 2022.
If you want to erase the current structure and data in favor of a new one that's easy.
If you want to convert your current structure to a different one, that might be pretty hard, but it's highly data related.
Let's consider your samples as the actual data you want to convert
Here are the issues and complications I see
color-1
is? what name does it have? that's human operation unless you have some ColorCode-ColorName tablecolor-N
keys? to get the property value cleanly you will need to reference them explicitly. (but I'm sure you can find other ways... without using JSON functions tho)JSON function samples
I've played around with the JSON data and created some sample queries, I hope trying them will help you understand what it means to manipulate JSON data, and choose if SQL Server is a fitting tool for your task