3

How can I get question_id field in this json file? I tried, but it returns null.

DECLARE @json NVARCHAR(MAX)
SET @json = 
 N'{ 
 "solution": "xxxxxxxxxxxxxxxxxxxxx",
 "options": [
 {
 "choice_id": 205073,
 "choice": "aaaa"
 },
 {
 "choice_id": 205074,
 "choice": "bbbb"
 },
 {
 "choice_id": 205075,
 "choice": "cccc"
 },
 {
 "choice_id": 205076,
 "choice": "dddd"
 }
 ],
 "question_id": 12345
 }' 
SELECT * FROM 
 OPENJSON ( @json, '$.options')
WITH ( 
 choice_id varchar(8000) '$.choice_id',
 question_id int '$.question_id'
 ) 

Result

enter image description here

Mikael Eriksson
22.3k5 gold badges63 silver badges106 bronze badges
asked Sep 28, 2017 at 20:51
0

1 Answer 1

7

You treat question_id as if it was a child to options when it is in fact a sibling to options.

You can use json_value in the column list to get the value for question_id.

select O.choice_id,
 json_value(@json, '$.question_id') as question_id
from openjson(@json, '$.options')
 with (
 choice_id varchar(8000) '$.choice_id'
 ) as O;

If you have an array of objects on the root you would first need to shred on $ to get one row per object and then use a cross apply to get the objects.

declare @json nvarchar(max)
set @json = N'
[
 {
 "solution":"xxxxxxxxxxxxxxxxxxxxx",
 "options":[
 {
 "choice_id":205073,
 "choice":"aaaa"
 },
 {
 "choice_id":205074,
 "choice":"bbbb"
 },
 {
 "choice_id":205075,
 "choice":"cccc"
 },
 {
 "choice_id":205076,
 "choice":"dddd"
 }
 ],
 "question_id":12345
 },
 {
 "solution":"xxxxxxxxxxxxxxxxxxxxx",
 "options":[
 {
 "choice_id":205073,
 "choice":"aaaa"
 },
 {
 "choice_id":205074,
 "choice":"bbbb"
 },
 {
 "choice_id":205075,
 "choice":"cccc"
 },
 {
 "choice_id":205076,
 "choice":"dddd"
 }
 ],
 "question_id":22345
 }
]' 
select json_value(T1.value, '$.question_id'),
 T2.choice_id
from openjson(@json, '$') as T1
 cross apply openjson(T1.value, '$.options') 
 with (choice_id varchar(8000))as T2;
answered Sep 29, 2017 at 5:53
0

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

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.