Avatar of Aleks
Aleks
Flag for United States of America asked on

2012 SQL to JSON Select

I am using MS SQL 2012. Is there a way to get results in a JSON format from a recordset and use them to pass them as a string to post to an URL ?

For example a simple query

SELECT FirstNm, LastNm, email 
FROM dbo.Users

Open in new window


So it returns:
{
  "first_name": "Aleks",
  "last_name": "Demo",
  "email_addresses": [
    {
      "email_address": "support@domain.com"
    }
  ]
}

Open in new window


Is this posible from SQL or do I need to do this afterwards in ASP. I am using ASP Classic.
ASPSQLJSON

Avatar of undefined
Last Comment
Aleks

8/22/2022 - Mon
ASKER CERTIFIED SOLUTION
HainKurt

THIS SOLUTION ONLY AVAILABLE TO MEMBERS.
View this solution by signing up for a free trial.
Members can start a 7-Day free trial and enjoy unlimited access to the platform.
See Pricing Options
Start Free Trial
GET A PERSONALIZED SOLUTION
Ask your own question & get feedback from real experts
Find out why thousands trust the EE community with their toughest problems.
HainKurt

from ASP

get result from sql as

SELECT FirstNm, LastNm, email 
FROM dbo.Users

Open in new window


then use asp

dim json_result as string
json_result = "{""first_name"": """ & RS("FirstNm") & """,  ""last_name"": """ & RS("LastNm") & """,  ""email_addresses"": [{""email_address"": """ & RS("email") & """}]}"

Open in new window


or try

dim json_result as string
json_result = "{first_name: '" & RS("FirstNm") & "',  last_name: '" & RS("LastNm") & "', email_addresses: [{email_address: '" & RS("email") & "'}]}"

Open in new window

Aleks

ASKER
Both return errors

Second and third:  Msg 156, Level 15, State 1, Line 2
Incorrect syntax near the keyword 'as'.

and the first one:

Msg 102, Level 15, State 1, Line 4
Incorrect syntax near ': '.
Msg 105, Level 15, State 1, Line 7
Unclosed quotation mark after the character string '
    }
  ]
}' as json_result
FROM dbo.Users
'.

I am using MS SQL 2012
Aleks

ASKER
I checked the first one and used:

SELECT
'{
  "first_name": "' + FirstNm + '",
  "last_name": "' + LastNm + '",
  "email_addresses": [
    {
      "email_address": "' + email + '"
    }
  ]
}' as json_result
FROM dbo.Users

Open in new window


It returns :
{    "first_name": "Jose",    "last_name": "JONES",    "email_addresses": [      {        "email_address": ""      }    ]  }

Which is valud JSON.  Thank you!
I started with Experts Exchange in 2004 and it's been a mainstay of my professional computing life since. It helped me launch a career as a programmer / Oracle data analyst
William Peck
Aleks

ASKER
Not there is a syntax error. it is displayed at the bottom.