4

I have a JSON column in one of the tables, and the JSON column has no key or property, only the value.

I tried to parse the column with JSON_Query and JSON_Value, but both of these functions only work if the JSON string has a key, but in my situation, the JSON string has no key.

So how can I parse the column from the top table to the bottom table in SQL Server like the image below?

enter image description here

5
  • What version of SQL Server? That does not look like valid JSON, so you probably won't be able to use the JSON functions.
    – Jacob H
    Commented Jan 31, 2019 at 22:38
  • Actually OPENJSON might work if you can convince SQL Server that the column is valid JSON :) Try something like this SELECT value FROM OPENJSON([JSON Column],'$')
    – Jacob H
    Commented Jan 31, 2019 at 22:45
  • Actually probably not unless you have valid JSON formatting. But your post doesn't show that.
    – Jacob H
    Commented Jan 31, 2019 at 22:49
  • You have a simple array. If 2016+ take a look at string_split() Commented Jan 31, 2019 at 23:16
  • This is a valid JSON column since I ran the ISJSON test with it. And this column actually have a key in a different table, but the developer processed the key and value into different columns in SQL. Neither OPENJSON and string_split() work.
    – Duyan Zhen
    Commented Feb 4, 2019 at 21:06

1 Answer 1

3

Please try this:

DECLARE @Table TABLE (ID INT, [JSONColumn] NVARCHAR(MAX));
INSERT INTO @Table(ID,[JSONColumn])VALUES
     (151616,'["B0107C57WO","B066EYU4IY"]')
    ,(151617,'["B0088MD64S"]')
;

SELECT t.ID,j.[value]
FROM @Table t
CROSS APPLY OPENJSON(t.JSONColumn) j
;
3
  • This works great so far, but since there are millions of record within the JSON Column, I will not be able to specify the value one by one. So instead of inserting specific value, can you do it as Id and JSON Column are columns within a SQL table? So I can extract the value from every JSON record instead of having to specify one by one?
    – Duyan Zhen
    Commented Feb 4, 2019 at 21:10
  • SELECT t.ID,j.[value] FROM [UseYourTableName] AS [t] CROSS APPLY OPENJSON(t.[ThatTableJSONColumnName]) AS [j]; Commented Feb 4, 2019 at 22:17
  • 1
    you rocked! Thank you so much for the help.
    – Duyan Zhen
    Commented Feb 4, 2019 at 23:45

Not the answer you're looking for? Browse other questions tagged or ask your own question.