Search code examples
sql-serveropen-json

OPENJSON - How to extract value from JSON object saved as NVARCHAR in SQL Server


There is a column RawData of type NVARCHAR which contains JSON object as strings

RawData 
-------------------------------------------------------
{"ID":1,--other key/value(s)--,"object":{--object1--}}
{"ID":2,--other key/value(s)--,"object":{--object2--}}
{"ID":3,--other key/value(s)--,"object":{--object3--}}
{"ID":4,--other key/value(s)--,"object":{--object4--}}
{"ID":5,--other key/value(s)--,"object":{--object5--}}

This JSON string is big (1kb) and currently the most used part of this json is object(200 bytes).

i want to extract object part of these json strings by using OPENJSON.and i was not able to achieve a solution but i think there is a solution.

The result that i want is:

RawData 
----------------
{--object1--}
{--object2--}
{--object3--}
{--object4--}
{--object5--}

My attempts so far

SELECT * 
FROM OPENJSON((SELECT RawData From DATA_TB FOR JSON PATH))

Solution

  • Looks like this should work for you.

    Sample data

    create table data_tb
    (
      RawData nvarchar(max)
    );
    
    insert into data_tb (RawData) values
    ('{"ID":1, "key": "value1", "object":{ "name": "alfred" }}'),
    ('{"ID":2, "key": "value2", "object":{ "name": "bert" }}'),
    ('{"ID":3, "key": "value3", "object":{ "name": "cecil" }}'),
    ('{"ID":4, "key": "value4", "object":{ "name": "dominique" }}'),
    ('{"ID":5, "key": "value5", "object":{ "name": "elise" }}');
    

    Solution

    select d.RawData, json_query(d.RawData, '$.object') as Object
    from data_tb d;
    

    See it in action: fiddle.