0

There is a VARCHAR column jsonString that has simple text that is formatted as JSON:

id         jsonString
1          {"topData":{"personName":"john","personAge":"20"}}
2          {"topData":{"personName":"mike","personAge":"30"}}
3          {"topData":{"personName":"sten","personAge":"50"}}

How to parse this string? It is not a JSON object, so do we need to cast it as JSON first?

select OPENJSON(cast(jsonString as JSON) 

I have tried many ways but couldn't extract personName and personAge as separate values.

3
  • Please who us the "many ways" you have tried. Commented Feb 28, 2021 at 22:49
  • According to the docs learn.microsoft.com/en-us/sql/t-sql/functions/…, "jsonExpression Is a Unicode character expression containing JSON text.". So there is no need to cast your string to anything at all. Commented Feb 28, 2021 at 22:54
  • did you suceed at the code? Commented Mar 1, 2021 at 18:45

1 Answer 1

1

Try something like this:

SELECT personName,
       personAge 
FROM NAME_OF_THE_TABLE
OUTER APPLY OPENJSON (jsonString)
WITH
(
    personName nvarchar(50) '$topData.personName',
    personAge tinyint '$topData.personAge'
)

You didn't mention the name of the table, so you can replace the NAME_OF_THE_TABLE by the real one

Sign up to request clarification or add additional context in comments.

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.