I have a JSON string which is the following:
[
{
"id": 103001058774,
"name": "status",
"label": "Status",
"description": "Ticket status",
"choices": {
"2": [
"Open",
"Open"
],
"3": [
"Pending",
"Pending"
],
"4": [
"Resolved",
"Resolved"
],
"5": [
"Closed",
"Closed"
],
"6": [
"Waiting on Customer",
"Awaiting your Reply"
],
"7": [
"Waiting on Third Party",
"Being Processed"
],
"8": [
"Assigned",
"Assigned"
]
}
}
]
I am trying to put this into a SQL table looking like the following from the CHOICES leg of the JSON:
id | agent_label | customer_label |
---|---|---|
2 | Open | Open |
3 | Pending | Pending |
4 | Resolved | Resolved |
5 | Closed | Closed |
6 | Waiting on Customer | Awaiting your Reply |
7 | Waiting on Third Party | Being Processed |
8 | Assigned | Assigned |
I already have this as a Query and I am on the right lines… But I don’t know how to strip out the ID numbers!:
DECLARE @jsonStatusesData NVARCHAR (MAX) = *'My JSON String'*
SELECT id = JSON_QUERY(j.value, $.choices')
FROM OPENJSON(@jsonStatusesData) AS j
I do have a few more lines in there I need to add in, but ultimately the table above is what I want to do. Of course, that SQL query is just returning the whole Choices branch and doesn’t help me at all.
Any help would be great! 🙂
Thanks,
Ash
2
Answers
You need a second level of
OPENJSON
to break out thechoices
array. And you need to read that array using theAS JSON
syntaxdb<>fiddle
This does the job for your sample data:
Assumptions:
choices
to unnest)choices
array, each object is an array of two scalar values that you want to put side by sidefiddle