Link to home
Start Free TrialLog in
Avatar of Aleks
AleksFlag 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.
ASKER CERTIFIED SOLUTION
Avatar of HainKurt
HainKurt
Flag of Canada image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
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

Avatar of 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
Avatar of 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!
Avatar of Aleks

ASKER

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