0
[
    {
        "Levelname": "LGA",
        "levelvalue": "Alimosho"
    },
    {
        "Levelname": "STATE",
        "levelvalue": "LAGOS"
    },
    {
        "Levelname": "SUB ZONE",
        "levelvalue": "LAGOS 2"
    },
    {
        "Levelname": "BRANCH",
        "levelvalue": "LAGOS 2"
    },
    {
        "Levelname": "ZONE",
        "levelvalue": "LAGOS"
    }
]

is there a way we can extract this data from JSON and put in the table format like:

Lga    STATE     SUB ZONE    BRANCH   ZONE
4
  • There's plenty of questions on Stack Overflow on how to consume JSON; what didn't you understand about them? What have you tried so far? Why didn't your attempts work?
    – Thom A
    Commented Jul 23, 2021 at 14:47
  • is there a way we can extract this data from JSON? where is the json? in JavaScript? C# , OR it is hard code in sql? Commented Jul 23, 2021 at 14:51
  • @AlirezaAhmadi we stored this data in table and want to extract from there. Commented Jul 23, 2021 at 14:52
  • see this: red-gate.com/simple-talk/sql/t-sql-programming/… Commented Jul 23, 2021 at 14:54

1 Answer 1

2

You need to explode out the array with OPENJSON and JSON_VALUE, then pivot the values back up into a single row

You could also use OPENJSON again instead of JSON_VALUE, and you could place the pivot on the outside if you prefer

SELECT j.*
FROM YourTable t
CROSS APPLY (
    SELECT *
    FROM (
        SELECT
            levelvalue = JSON_VALUE(j.value, '$.levelvalue'),
            Levelname =  JSON_VALUE(j.value, '$.Levelname')
        FROM OPENJSON(t.JsonColumn) j
    ) j
    PIVOT (
      MAX(levelvalue) FOR Levelname IN
        (LGA, STATE, [SUB ZONE], BRANCH, ZONE)
    ) pvt
) j;
0

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