Manipulate JSON data in SQL Server |
JavaScript Object Notation (JSON) is a lightweight popular data exchangeable format used across modern IoT platforms, web and mobile applications etc. It is a language independent textual data format. JavaScript Object Notation (JSON) is also used for storing unstructured data in log files or NoSQL Databases such as Microsoft Azure Cosmos DB. Many RESTful web services that allow us to store and retrieve JSON formatted texts among different protocols using different Endpoints. The example of JSON text is as follows,
- Read JSON data from table
- Modify JSON data in a table
- Validate JSON objects
- Convert array of JSON objects into table format
Lets see how to retrieve JSON data from a table?
Read JSON data from table
Here we are using JSON_VALUE predefined function to retrieve column values from JSON objects.In this example, we are using country wise sales table to read customer and product list details.
The JSON_VALUE function returns null when there is an nested array of objects like you can see in the above example, we are having customer array objects in this we are having nested multiple products list, when you see the return result you can see the NULL products because the JSON_VALUE function returns null when there is nested objects. In order to read this value we need to use JSON_QUERY function instead.
Modify JSON data in a table
The JSON_MODIFY function is used to update the values of a property in JSON string and return the updated JSON string. The following example illustrates how to update a value of a property in a variable that contains JSON?.In order to update the nested object values, your query should be like this,
Validate JSON data
In order to validate JSON data we are using ISJSON() straightforward built-in function. The ISJSON() tests whether a string contains valid JSON or not. The following example returns rows in which the column "Data" contains valid JSON.The returned result is,
Convert JSON objects into table format
The OPENJSON function is used to easily convert JSON data to rows and colmns. The OPENJSON provides a row set view over a JSON document. You can explicitly specify the columns in the row set and the JSON property paths used to populate the columns. With OPENJSON function you can easily import JSON files into SQL server or convert JSON data into table format. The following example returns a nested objects by specifying the path:By without specifying path, your query should be like this:
The result is,
Suppose, If you want to read the top level object values the query should be:
The OPENJSON uses key value pair to retrieve JSON data as well as it removes duplicate property values.
Comments