0

I am trying to parse a column

Example Column Data

[{"id":"100190","role":"Company"},{"id":"1049","role":"Person"}]

Example Table

| item | perm                                                             | 
|------|------------------------------------------------------------------|
| a100 | NULL                                                             |
| a101 | NULL                                                             |
| b200 | [{"id":"100190","role":"Company"},{"id":"1049","role":"Person"}] |
| b201 | [{"id":"100190","role":"Company"},{"id":"1049","role":"Person"}] | 

Example Procedure

declare @id int = 1049

select *
from someTable
where contains(openjson(perm, '$') with (
  id int '$.id'
), @id)

**Expeced Output **

| item | perm                                                             | 
|------|------------------------------------------------------------------|
| b200 | [{"id":"100190","role":"Company"},{"id":"1049","role":"Person"}] |
| b201 | [{"id":"100190","role":"Company"},{"id":"1049","role":"Person"}] | 

How do I select rows that contain a given id from an embedded array of JSON?

2 Answers 2

5

Using CROSS APPLY on your JSON will get you what you want.

Here's an example you can run in SSMS:

-- Create table --
DECLARE @Data TABLE ( item VARCHAR(10), perm NVARCHAR(MAX) );

-- Add sample data --
INSERT INTO @Data ( item, perm ) VALUES
( 'a100', NULL ),
( 'a101', NULL ),
( 'b200', '[{"id":"100190","role":"Company"},{"id":"1049","role":"Person"}]' ),
( 'b201', '[{"id":"100190","role":"Company"},{"id":"1049","role":"Person"}]' );

-- Create id param --
DECLARE @id INT = 1049;

-- Select rows where JSON.id equals @id --
SELECT
    d.item, d.perm, j.id
FROM @Data AS d
CROSS APPLY (

    SELECT id FROM OPENJSON( d.perm ) WITH (
        id INT '$.id'
    )

) AS j
WHERE
    j.id = @id
ORDER BY
    d.item;

Which returns:

+------+------------------------------------------------------------------+------+
| item |                               perm                               |  id  |
+------+------------------------------------------------------------------+------+
| b200 | [{"id":"100190","role":"Company"},{"id":"1049","role":"Person"}] | 1049 |
| b201 | [{"id":"100190","role":"Company"},{"id":"1049","role":"Person"}] | 1049 |
+------+------------------------------------------------------------------+------+
Sign up to request clarification or add additional context in comments.

Comments

2

You could use OPENJSON to parse JSON array and CROSS APPLY to filter rows:

declare @id int = 1049;

select t.*
from t
cross apply(select * from OPENJSON(t.perm, '$') WITH (id INT '$.id') where id = @id) sub;

db<>fiddle demo

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.