How to rename JSON key in SQL Server (T-SQL)?
If you have been using the JSON_MODIFY()
function to modify JSON documents in SQL Server, then you may be used to modifying the value
of the key/value
attribute. part. But did you know you can also modify the key
part?
The trick to doing this is to copy the value to a new key and then delete the old key.
Here's a basic example of what I mean.
-- Declare a variable and assign some JSON to it DECLARE @data NVARCHAR(50)='{"Name":"Homer"}' -- Print the current JSON PRINT @data -- Rename the key (by copying the value to a new key, then deleting the old one) SET @data= JSON_MODIFY( JSON_MODIFY(@data,'$.Handle', JSON_VALUE(@data,'$.Name')), '$.Name', NULL ) -- Print the new JSON PRINT @data
Result:
{"Name":"Homer"} {"Handle":"Homer"}
This will print out the original key/value pairs, followed by the new key/value pairs.
While we can say we "renamed" the key, we actually just created a new key, copied the existing value to that new key, and then set the old key to NULL to delete it.
In this example, we use the JSON_VALUE()
function to extract the value.
Number
Need to be careful when copying data to a new key. By default, SQL Server encloses it in double quotes. This may or may not be what you want.
However, if you copy a numeric value, you probably want it to still be a numeric value (i.e. without double quotes). In this case, you need to use the CAST()
function to convert it to a numeric data type. Here's an example:
-- Declare a variable and assign some JSON to it DECLARE @data NVARCHAR(50)='{"Residents":768}' -- Print the current JSON PRINT @data -- Rename the key (by copying the value to a new key, then deleting the old one) SET @data= JSON_MODIFY( JSON_MODIFY(@data,'$.Population', CAST(JSON_VALUE(@data,'$.Residents') AS int)), '$.Residents', NULL ) -- Print the new JSON PRINT @data
Result:
{"Residents":768} {"Population":768}
So the result is a number.
If we remove the CAST()
function from this example, we get the result:
-- Declare a variable and assign some JSON to it DECLARE @data NVARCHAR(50)='{"Residents": 768}' -- Print the current JSON PRINT @data -- Rename the key (by copying the value to a new key, then deleting the old one) SET @data= JSON_MODIFY( JSON_MODIFY(@data,'$.Population', JSON_VALUE(@data,'$.Residents')), '$.Residents', NULL ) -- Print the new JSON PRINT @data
The result:
{"Residents": 768} {"Population":"768"}
Therefore , in this case, we not only renamed the keys, but also changed the (JSON) data type from number to string.
Note, JSON does not distinguish between different number types. It has only one numeric type: number.
key keys and spaces
In this example, I renamed an existing key to a new key that contains spaces (it Consists of two words separated by spaces).
Because the new key contains spaces, I need to surround the key with double quotes. If you don't do this, errors will occur.
-- Declare a variable and assign some JSON to it DECLARE @data NVARCHAR(50)='{"Population":68}' -- Print the current JSON PRINT @data -- Rename the key (by copying the value to a new key, then deleting the old one) SET @data= JSON_MODIFY( JSON_MODIFY(@data,'$."Average IQ"', CAST(JSON_VALUE(@data,'$.Population') AS int)), '$.Population', NULL ) -- Print the new JSON PRINT @data
Result:
{"Population":68} {"Average IQ":68}
Nested properties
If the properties are nested, there is no problem. Just use dot notation to reference it.
DECLARE @data NVARCHAR(4000) SET @data=N'{ "Suspect": { "Name": "Homer Simpson", "Hobbies": ["Eating", "Sleeping", "Base Jumping"] } }' PRINT @data SET @data= JSON_MODIFY( JSON_MODIFY(@data,'$.Suspect.Qualifications', JSON_QUERY(@data,'$.Suspect.Hobbies')), '$.Suspect.Hobbies', NULL ) PRINT @data
Result:
{ "Suspect": { "Name": "Homer Simpson", "Hobbies": ["Eating", "Sleeping", "Base Jumping"] } } { "Suspect": { "Name": "Homer Simpson" ,"Qualifications":["Eating", "Sleeping", "Base Jumping"]} }
You may also notice that this example uses the JSON_QUERY()
function to extract the value instead of the previous one Use JSON_VALUE()
as an example.
This is because in this case, we are extracting an array, and JSON_VALUE()
cannot extract the entire array (it can only extract scalar values from the array). On the other hand, the JSON_QUERY()
function extracts objects and arrays, but not scalar values.
Related recommendations: "SQL Tutorial" "MySQL Tutorial"
The above is the detailed content of How to rename JSON key in SQL Server (T-SQL)?. For more information, please follow other related articles on the PHP Chinese website!

Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

AI Hentai Generator
Generate AI Hentai for free.

Hot Article

Hot Tools

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

Hot Topics



HQL and SQL are compared in the Hibernate framework: HQL (1. Object-oriented syntax, 2. Database-independent queries, 3. Type safety), while SQL directly operates the database (1. Database-independent standards, 2. Complex executable queries and data manipulation).

"Usage of Division Operation in OracleSQL" In OracleSQL, division operation is one of the common mathematical operations. During data query and processing, division operations can help us calculate the ratio between fields or derive the logical relationship between specific values. This article will introduce the usage of division operation in OracleSQL and provide specific code examples. 1. Two ways of division operations in OracleSQL In OracleSQL, division operations can be performed in two different ways.

Oracle and DB2 are two commonly used relational database management systems, each of which has its own unique SQL syntax and characteristics. This article will compare and differ between the SQL syntax of Oracle and DB2, and provide specific code examples. Database connection In Oracle, use the following statement to connect to the database: CONNECTusername/password@database. In DB2, the statement to connect to the database is as follows: CONNECTTOdataba

Solution: 1. Check whether the logged-in user has sufficient permissions to access or operate the database, and ensure that the user has the correct permissions; 2. Check whether the account of the SQL Server service has permission to access the specified file or folder, and ensure that the account Have sufficient permissions to read and write the file or folder; 3. Check whether the specified database file has been opened or locked by other processes, try to close or release the file, and rerun the query; 4. Try as administrator Run Management Studio as etc.

Performance optimization methods for converting PHP arrays to JSON include: using JSON extensions and the json_encode() function; adding the JSON_UNESCAPED_UNICODE option to avoid character escaping; using buffers to improve loop encoding performance; caching JSON encoding results; and considering using a third-party JSON encoding library.

Database technology competition: What are the differences between Oracle and SQL? In the database field, Oracle and SQL Server are two highly respected relational database management systems. Although they both belong to the category of relational databases, there are many differences between them. In this article, we will delve into the differences between Oracle and SQL Server, as well as their features and advantages in practical applications. First of all, there are differences in syntax between Oracle and SQL Server.

Annotations in the Jackson library control JSON serialization and deserialization: Serialization: @JsonIgnore: Ignore the property @JsonProperty: Specify the name @JsonGetter: Use the get method @JsonSetter: Use the set method Deserialization: @JsonIgnoreProperties: Ignore the property @ JsonProperty: Specify name @JsonCreator: Use constructor @JsonDeserialize: Custom logic

The difference between Oracle and SQL and analysis of application scenarios In the database field, Oracle and SQL are two frequently mentioned terms. Oracle is a relational database management system (RDBMS), and SQL (StructuredQueryLanguage) is a standardized language for managing relational databases. While they are somewhat related, there are also some significant differences. First of all, by definition, Oracle is a specific database management system, consisting of
