MySQL to Json

Collapse
X
 
  • Time
  • Show
Clear All
new posts
  • crocodilu2008
    New Member
    • Sep 2008
    • 9

    MySQL to Json

    Why this not working ?
    Our SQL table.

    Code:
    username   email
    
    tommy 	tommy@example.com
    jane  	jane@example.com
    jack  	jack@example.com
    Code:
    SELECT 
         CONCAT("[",
              GROUP_CONCAT(
                   CONCAT("{username:'",username,"'"),
                   CONCAT(",email:'",email),"'}")
              )
         ,"]") 
    AS json FROM users;
    A MySQL-query that returns JSON.

    Code:
    [
         {username:'tommy',email:'tommy@example.com'},
         {username:'jane',email:'jane@example.com'},
         {username:'jack',email:'jack@example.com'}
    ]
    I found this here Mysql to Json

    Thanks
    Last edited by Atli; Sep 24 '08, 06:18 PM. Reason: Replaced real emails with example.com
  • Atli
    Recognized Expert Expert
    • Nov 2006
    • 5062

    #2
    Hi.

    How is it not working?
    Are you getting any error messages?

    We can't really help unless we know what the problem is.
    Simply knowing that there is a problem is of very little use.

    Comment

    • crocodilu2008
      New Member
      • Sep 2008
      • 9

      #3
      Always i have this error
      "You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near ')
      AS json FROM users' at line 7"

      Comment

      • Atli
        Recognized Expert Expert
        • Nov 2006
        • 5062

        #4
        The expression you use with the GROUP_CONCAT function is invalid.

        You are basically doing this:
        [code=mysql]GROUP_CONCAT("s tring", "string")[/code]
        while the function expects something more like this:
        [code=mysql]GROUP_CONCAT("e xpression")[/code]

        To use the CONCAT functions like you do, you would have to enclose them both in their own CONCAT function, so that they returned a single string to the GROUP_CONCAT function.

        Like:
        [code=mysql]
        GROUP_CONCAT(
        CONCAT(
        CONCAT("{userna me:'", username, "'"),
        CONCAT(",email: '", email, "'}")
        )
        )[/code]

        Comment

        Working...