MySQL: Return JSON from a standard SQL QueryExport Postgres table as jsonCan MySQL 5.1 read a MySQL 5.5...

How can I block email signup overlays or javascript popups in Safari?

How to implement a feedback to keep the DC gain at zero for this conceptual passive filter?

What was this official D&D 3.5e Lovecraft-flavored rulebook?

What does chmod -u do?

Count the occurrence of each unique word in the file

2.8 Why are collections grayed out? How can I open them?

Is it better practice to read straight from sheet music rather than memorize it?

Can Legal Documents Be Siged In Non-Standard Pen Colors?

Where does the bonus feat in the cleric starting package come from?

Aragorn's "guise" in the Orthanc Stone

Not using 's' for he/she/it

Removing files under particular conditions (number of files, file age)

Why Shazam when there is already Superman?

Lowest total scrabble score

Start making guitar arrangements

The IT department bottlenecks progress. How should I handle this?

Biological Blimps: Propulsion

What is this called? Old film camera viewer?

Delivering sarcasm

Loading commands from file

Why does the Sun have different day lengths, but not the gas giants?

How do you make your own symbol when Detexify fails?

Creepy dinosaur pc game identification

Did Swami Prabhupada reject Advaita?



MySQL: Return JSON from a standard SQL Query


Export Postgres table as jsonCan MySQL 5.1 read a MySQL 5.5 MyISAM file?Use MySQL to regularly do multi-way joins on 100+ GB tables?How safe is it to widen a column in MySQL?25.000+ rows - MySQL SELECT consecutive numbers performance issueConcurrency when simulating autoincrement with triggers on MySQLPostgres query to return JSON object keys as arrayJSON MySQL 5.7 queryWorking with JSON data MySQLfunction return multiple json rowsSimplifying database structure with many unequal vectors













4















I have read about JSON objects and the JSON object type. I only want to do a select and it return JSON. I do not necessarily want to store a JSON object. Serialization per se it not my question. The columns are regular Varchar, Int, etc. columns, no JSON Objects, "normal" database rows.



Can I do a regular old SELECT and return JSON for MySQL?



Isn't this what FOR JSON in SQL SERVER and rows_for_json do in PostgreSQL?



They seemed ahead in this are but I didn't want to fool myself.



I found this question from 2016:
https://stackoverflow.com/questions/35324795/mysql-5-7-return-row-as-json-using-new-json-features










share|improve this question




















  • 1





    there is no rows_for_json in postgresql

    – Evan Carroll
    Dec 2 '17 at 23:21











  • What about row_to_json? Maybe that's what I meant.

    – johnny
    Dec 4 '17 at 13:15






  • 1





    See also stackoverflow.com/a/11169658/199364, stackoverflow.com/a/41760134/199364, stackoverflow.com/a/35957518/199364,

    – ToolmakerSteve
    Mar 7 at 0:51
















4















I have read about JSON objects and the JSON object type. I only want to do a select and it return JSON. I do not necessarily want to store a JSON object. Serialization per se it not my question. The columns are regular Varchar, Int, etc. columns, no JSON Objects, "normal" database rows.



Can I do a regular old SELECT and return JSON for MySQL?



Isn't this what FOR JSON in SQL SERVER and rows_for_json do in PostgreSQL?



They seemed ahead in this are but I didn't want to fool myself.



I found this question from 2016:
https://stackoverflow.com/questions/35324795/mysql-5-7-return-row-as-json-using-new-json-features










share|improve this question




















  • 1





    there is no rows_for_json in postgresql

    – Evan Carroll
    Dec 2 '17 at 23:21











  • What about row_to_json? Maybe that's what I meant.

    – johnny
    Dec 4 '17 at 13:15






  • 1





    See also stackoverflow.com/a/11169658/199364, stackoverflow.com/a/41760134/199364, stackoverflow.com/a/35957518/199364,

    – ToolmakerSteve
    Mar 7 at 0:51














4












4








4


2






I have read about JSON objects and the JSON object type. I only want to do a select and it return JSON. I do not necessarily want to store a JSON object. Serialization per se it not my question. The columns are regular Varchar, Int, etc. columns, no JSON Objects, "normal" database rows.



Can I do a regular old SELECT and return JSON for MySQL?



Isn't this what FOR JSON in SQL SERVER and rows_for_json do in PostgreSQL?



They seemed ahead in this are but I didn't want to fool myself.



I found this question from 2016:
https://stackoverflow.com/questions/35324795/mysql-5-7-return-row-as-json-using-new-json-features










share|improve this question
















I have read about JSON objects and the JSON object type. I only want to do a select and it return JSON. I do not necessarily want to store a JSON object. Serialization per se it not my question. The columns are regular Varchar, Int, etc. columns, no JSON Objects, "normal" database rows.



Can I do a regular old SELECT and return JSON for MySQL?



Isn't this what FOR JSON in SQL SERVER and rows_for_json do in PostgreSQL?



They seemed ahead in this are but I didn't want to fool myself.



I found this question from 2016:
https://stackoverflow.com/questions/35324795/mysql-5-7-return-row-as-json-using-new-json-features







mysql json






share|improve this question















share|improve this question













share|improve this question




share|improve this question








edited Dec 2 '17 at 13:49









Vérace

16.3k33550




16.3k33550










asked Dec 1 '17 at 20:44









johnnyjohnny

2321613




2321613








  • 1





    there is no rows_for_json in postgresql

    – Evan Carroll
    Dec 2 '17 at 23:21











  • What about row_to_json? Maybe that's what I meant.

    – johnny
    Dec 4 '17 at 13:15






  • 1





    See also stackoverflow.com/a/11169658/199364, stackoverflow.com/a/41760134/199364, stackoverflow.com/a/35957518/199364,

    – ToolmakerSteve
    Mar 7 at 0:51














  • 1





    there is no rows_for_json in postgresql

    – Evan Carroll
    Dec 2 '17 at 23:21











  • What about row_to_json? Maybe that's what I meant.

    – johnny
    Dec 4 '17 at 13:15






  • 1





    See also stackoverflow.com/a/11169658/199364, stackoverflow.com/a/41760134/199364, stackoverflow.com/a/35957518/199364,

    – ToolmakerSteve
    Mar 7 at 0:51








1




1





there is no rows_for_json in postgresql

– Evan Carroll
Dec 2 '17 at 23:21





there is no rows_for_json in postgresql

– Evan Carroll
Dec 2 '17 at 23:21













What about row_to_json? Maybe that's what I meant.

– johnny
Dec 4 '17 at 13:15





What about row_to_json? Maybe that's what I meant.

– johnny
Dec 4 '17 at 13:15




1




1





See also stackoverflow.com/a/11169658/199364, stackoverflow.com/a/41760134/199364, stackoverflow.com/a/35957518/199364,

– ToolmakerSteve
Mar 7 at 0:51





See also stackoverflow.com/a/11169658/199364, stackoverflow.com/a/41760134/199364, stackoverflow.com/a/35957518/199364,

– ToolmakerSteve
Mar 7 at 0:51










4 Answers
4






active

oldest

votes


















8














Took a bit of figuring out (more used to PostgreSQL where things are much easier!), but if you consult the fine manual here, under 12.16.2 Functions That Create JSON Values, there's the JSON_ARRAY function, but it's not much use really - at least in this case!



To answer the question "select and it return JSON", there are two ways of doing this, both rather painful!



You can either




  • use a "hack" - see the db-fiddle here,


  • or use one of the new MySQL supplied JSON functions here - which, ironically, appears to be even more of a hack than the hack itself! Only with MySQL! :-) (fiddle here).



Both answers use the MySQL GROUP_CONCAT function - this post helped. You might want to set the group_concat_max_len system variable to a bit more than its default (a paltry 1024)!



The first query is, as you can imagine, messy (DDL and DML at the bottom of this answer):



SELECT CONCAT('[', better_result, ']') AS best_result FROM
(
SELECT GROUP_CONCAT('{', my_json, '}' SEPARATOR ',') AS better_result FROM
(
SELECT
CONCAT
(
'"name_field":' , '"', name_field , '"', ','
'"address_field":', '"', address_field, '"', ','
'"contact_age":' , contact_age
) AS my_json
FROM contact
) AS more_json
) AS yet_more_json;


Result:



[{"name_field":"Mary","address_field":"address one","contact_age":25},{"name_field":"Fred","address_field":"address two","contact_age":35},{"name_field":"Bill","address_field":"address three","contact_age":47}]


which is correct, but, let's face it, a bit of a nightmare!



Then there's the MySQL JSON_ARRAY() approach (which is even messier - thanks MySQL for your (non-existent) implementation of the TRANSLATE() function!).



SELECT
CONCAT
('[', REPLACE
(
REPLACE
(
GROUP_CONCAT
(
JSON_ARRAY
(
'name_field:', name_field,
'address_field:', address_field,
'age_field:', contact_age
) SEPARATOR ','
), '[', '{'
), ']', '}'
), ']'
)
AS best_result2
FROM contact


Same result!



====  TABLE CREATION and INSERT DDL and DML ============

CREATE TABLE contact
(
name_field VARCHAR (5) NOT NULL,
address_field VARCHAR (20) NOT NULL,
contact_age INTEGER NOT NULL
);

INSERT INTO contact
VALUES
('Mary', 'address one', 25),
('Fred', 'address two', 35),
('Bill', 'address three', 47);





share|improve this answer

































    6














    Converting a row to json



    It doesn't sound to me like you want to aggregate JSON. You state you want the equivalent of row_to_json, if so then I suggest checking out the much simpler JSON_OBJECT



    SELECT JSON_OBJECT(
    'name_field', name_field,
    'address_field', address_field,
    'contact_age', contact_age
    )
    FROM contact;


    Aggregating JSON



    As a side note, if you do need to aggregate a resultset to json. then the upcoming MySQL 8 will do that for you.





    • JSON_ARRAYAGG() Return result set as a single JSON array


    • JSON_OBJECTAGG()` Return result set as a single JSON object






    share|improve this answer

































      2














      This will give you the same answer, but a lot easier code. I just used json_object with group_concat to simplify the other answer.



      select 
      concat('[',
      GROUP_CONCAT(
      JSON_OBJECT(
      'name_field', name_field
      ,'address_field', address_field
      ,'contact_age', contact_age
      )
      SEPARATOR ',')
      ,']')
      from contact;





      share|improve this answer

































        0














        For an array of JSON objects (one object per row in query), you can do this:



        SELECT JSON_ARRAYAGG(JSON_OBJECT("fieldA", fieldA, "fieldB", fieldB)) 
        FROM table;


        It would result in a single JSON array containing all entries:



        [
        {
        "fieldA": "value",
        "fieldB": "value"
        },
        ...
        ]


        Unfortunately, MySQL does not allow for selecting all fields with *. This would be awesome, but does not work:



        SELECT JSON_ARRAYAGG(JSON_OBJECT(*)) FROM table;





        share|improve this answer








        New contributor




        Eneko Alonso is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
        Check out our Code of Conduct.




















          Your Answer








          StackExchange.ready(function() {
          var channelOptions = {
          tags: "".split(" "),
          id: "182"
          };
          initTagRenderer("".split(" "), "".split(" "), channelOptions);

          StackExchange.using("externalEditor", function() {
          // Have to fire editor after snippets, if snippets enabled
          if (StackExchange.settings.snippets.snippetsEnabled) {
          StackExchange.using("snippets", function() {
          createEditor();
          });
          }
          else {
          createEditor();
          }
          });

          function createEditor() {
          StackExchange.prepareEditor({
          heartbeatType: 'answer',
          autoActivateHeartbeat: false,
          convertImagesToLinks: false,
          noModals: true,
          showLowRepImageUploadWarning: true,
          reputationToPostImages: null,
          bindNavPrevention: true,
          postfix: "",
          imageUploader: {
          brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
          contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
          allowUrls: true
          },
          onDemand: true,
          discardSelector: ".discard-answer"
          ,immediatelyShowMarkdownHelp:true
          });


          }
          });














          draft saved

          draft discarded


















          StackExchange.ready(
          function () {
          StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fdba.stackexchange.com%2fquestions%2f192208%2fmysql-return-json-from-a-standard-sql-query%23new-answer', 'question_page');
          }
          );

          Post as a guest















          Required, but never shown

























          4 Answers
          4






          active

          oldest

          votes








          4 Answers
          4






          active

          oldest

          votes









          active

          oldest

          votes






          active

          oldest

          votes









          8














          Took a bit of figuring out (more used to PostgreSQL where things are much easier!), but if you consult the fine manual here, under 12.16.2 Functions That Create JSON Values, there's the JSON_ARRAY function, but it's not much use really - at least in this case!



          To answer the question "select and it return JSON", there are two ways of doing this, both rather painful!



          You can either




          • use a "hack" - see the db-fiddle here,


          • or use one of the new MySQL supplied JSON functions here - which, ironically, appears to be even more of a hack than the hack itself! Only with MySQL! :-) (fiddle here).



          Both answers use the MySQL GROUP_CONCAT function - this post helped. You might want to set the group_concat_max_len system variable to a bit more than its default (a paltry 1024)!



          The first query is, as you can imagine, messy (DDL and DML at the bottom of this answer):



          SELECT CONCAT('[', better_result, ']') AS best_result FROM
          (
          SELECT GROUP_CONCAT('{', my_json, '}' SEPARATOR ',') AS better_result FROM
          (
          SELECT
          CONCAT
          (
          '"name_field":' , '"', name_field , '"', ','
          '"address_field":', '"', address_field, '"', ','
          '"contact_age":' , contact_age
          ) AS my_json
          FROM contact
          ) AS more_json
          ) AS yet_more_json;


          Result:



          [{"name_field":"Mary","address_field":"address one","contact_age":25},{"name_field":"Fred","address_field":"address two","contact_age":35},{"name_field":"Bill","address_field":"address three","contact_age":47}]


          which is correct, but, let's face it, a bit of a nightmare!



          Then there's the MySQL JSON_ARRAY() approach (which is even messier - thanks MySQL for your (non-existent) implementation of the TRANSLATE() function!).



          SELECT
          CONCAT
          ('[', REPLACE
          (
          REPLACE
          (
          GROUP_CONCAT
          (
          JSON_ARRAY
          (
          'name_field:', name_field,
          'address_field:', address_field,
          'age_field:', contact_age
          ) SEPARATOR ','
          ), '[', '{'
          ), ']', '}'
          ), ']'
          )
          AS best_result2
          FROM contact


          Same result!



          ====  TABLE CREATION and INSERT DDL and DML ============

          CREATE TABLE contact
          (
          name_field VARCHAR (5) NOT NULL,
          address_field VARCHAR (20) NOT NULL,
          contact_age INTEGER NOT NULL
          );

          INSERT INTO contact
          VALUES
          ('Mary', 'address one', 25),
          ('Fred', 'address two', 35),
          ('Bill', 'address three', 47);





          share|improve this answer






























            8














            Took a bit of figuring out (more used to PostgreSQL where things are much easier!), but if you consult the fine manual here, under 12.16.2 Functions That Create JSON Values, there's the JSON_ARRAY function, but it's not much use really - at least in this case!



            To answer the question "select and it return JSON", there are two ways of doing this, both rather painful!



            You can either




            • use a "hack" - see the db-fiddle here,


            • or use one of the new MySQL supplied JSON functions here - which, ironically, appears to be even more of a hack than the hack itself! Only with MySQL! :-) (fiddle here).



            Both answers use the MySQL GROUP_CONCAT function - this post helped. You might want to set the group_concat_max_len system variable to a bit more than its default (a paltry 1024)!



            The first query is, as you can imagine, messy (DDL and DML at the bottom of this answer):



            SELECT CONCAT('[', better_result, ']') AS best_result FROM
            (
            SELECT GROUP_CONCAT('{', my_json, '}' SEPARATOR ',') AS better_result FROM
            (
            SELECT
            CONCAT
            (
            '"name_field":' , '"', name_field , '"', ','
            '"address_field":', '"', address_field, '"', ','
            '"contact_age":' , contact_age
            ) AS my_json
            FROM contact
            ) AS more_json
            ) AS yet_more_json;


            Result:



            [{"name_field":"Mary","address_field":"address one","contact_age":25},{"name_field":"Fred","address_field":"address two","contact_age":35},{"name_field":"Bill","address_field":"address three","contact_age":47}]


            which is correct, but, let's face it, a bit of a nightmare!



            Then there's the MySQL JSON_ARRAY() approach (which is even messier - thanks MySQL for your (non-existent) implementation of the TRANSLATE() function!).



            SELECT
            CONCAT
            ('[', REPLACE
            (
            REPLACE
            (
            GROUP_CONCAT
            (
            JSON_ARRAY
            (
            'name_field:', name_field,
            'address_field:', address_field,
            'age_field:', contact_age
            ) SEPARATOR ','
            ), '[', '{'
            ), ']', '}'
            ), ']'
            )
            AS best_result2
            FROM contact


            Same result!



            ====  TABLE CREATION and INSERT DDL and DML ============

            CREATE TABLE contact
            (
            name_field VARCHAR (5) NOT NULL,
            address_field VARCHAR (20) NOT NULL,
            contact_age INTEGER NOT NULL
            );

            INSERT INTO contact
            VALUES
            ('Mary', 'address one', 25),
            ('Fred', 'address two', 35),
            ('Bill', 'address three', 47);





            share|improve this answer




























              8












              8








              8







              Took a bit of figuring out (more used to PostgreSQL where things are much easier!), but if you consult the fine manual here, under 12.16.2 Functions That Create JSON Values, there's the JSON_ARRAY function, but it's not much use really - at least in this case!



              To answer the question "select and it return JSON", there are two ways of doing this, both rather painful!



              You can either




              • use a "hack" - see the db-fiddle here,


              • or use one of the new MySQL supplied JSON functions here - which, ironically, appears to be even more of a hack than the hack itself! Only with MySQL! :-) (fiddle here).



              Both answers use the MySQL GROUP_CONCAT function - this post helped. You might want to set the group_concat_max_len system variable to a bit more than its default (a paltry 1024)!



              The first query is, as you can imagine, messy (DDL and DML at the bottom of this answer):



              SELECT CONCAT('[', better_result, ']') AS best_result FROM
              (
              SELECT GROUP_CONCAT('{', my_json, '}' SEPARATOR ',') AS better_result FROM
              (
              SELECT
              CONCAT
              (
              '"name_field":' , '"', name_field , '"', ','
              '"address_field":', '"', address_field, '"', ','
              '"contact_age":' , contact_age
              ) AS my_json
              FROM contact
              ) AS more_json
              ) AS yet_more_json;


              Result:



              [{"name_field":"Mary","address_field":"address one","contact_age":25},{"name_field":"Fred","address_field":"address two","contact_age":35},{"name_field":"Bill","address_field":"address three","contact_age":47}]


              which is correct, but, let's face it, a bit of a nightmare!



              Then there's the MySQL JSON_ARRAY() approach (which is even messier - thanks MySQL for your (non-existent) implementation of the TRANSLATE() function!).



              SELECT
              CONCAT
              ('[', REPLACE
              (
              REPLACE
              (
              GROUP_CONCAT
              (
              JSON_ARRAY
              (
              'name_field:', name_field,
              'address_field:', address_field,
              'age_field:', contact_age
              ) SEPARATOR ','
              ), '[', '{'
              ), ']', '}'
              ), ']'
              )
              AS best_result2
              FROM contact


              Same result!



              ====  TABLE CREATION and INSERT DDL and DML ============

              CREATE TABLE contact
              (
              name_field VARCHAR (5) NOT NULL,
              address_field VARCHAR (20) NOT NULL,
              contact_age INTEGER NOT NULL
              );

              INSERT INTO contact
              VALUES
              ('Mary', 'address one', 25),
              ('Fred', 'address two', 35),
              ('Bill', 'address three', 47);





              share|improve this answer















              Took a bit of figuring out (more used to PostgreSQL where things are much easier!), but if you consult the fine manual here, under 12.16.2 Functions That Create JSON Values, there's the JSON_ARRAY function, but it's not much use really - at least in this case!



              To answer the question "select and it return JSON", there are two ways of doing this, both rather painful!



              You can either




              • use a "hack" - see the db-fiddle here,


              • or use one of the new MySQL supplied JSON functions here - which, ironically, appears to be even more of a hack than the hack itself! Only with MySQL! :-) (fiddle here).



              Both answers use the MySQL GROUP_CONCAT function - this post helped. You might want to set the group_concat_max_len system variable to a bit more than its default (a paltry 1024)!



              The first query is, as you can imagine, messy (DDL and DML at the bottom of this answer):



              SELECT CONCAT('[', better_result, ']') AS best_result FROM
              (
              SELECT GROUP_CONCAT('{', my_json, '}' SEPARATOR ',') AS better_result FROM
              (
              SELECT
              CONCAT
              (
              '"name_field":' , '"', name_field , '"', ','
              '"address_field":', '"', address_field, '"', ','
              '"contact_age":' , contact_age
              ) AS my_json
              FROM contact
              ) AS more_json
              ) AS yet_more_json;


              Result:



              [{"name_field":"Mary","address_field":"address one","contact_age":25},{"name_field":"Fred","address_field":"address two","contact_age":35},{"name_field":"Bill","address_field":"address three","contact_age":47}]


              which is correct, but, let's face it, a bit of a nightmare!



              Then there's the MySQL JSON_ARRAY() approach (which is even messier - thanks MySQL for your (non-existent) implementation of the TRANSLATE() function!).



              SELECT
              CONCAT
              ('[', REPLACE
              (
              REPLACE
              (
              GROUP_CONCAT
              (
              JSON_ARRAY
              (
              'name_field:', name_field,
              'address_field:', address_field,
              'age_field:', contact_age
              ) SEPARATOR ','
              ), '[', '{'
              ), ']', '}'
              ), ']'
              )
              AS best_result2
              FROM contact


              Same result!



              ====  TABLE CREATION and INSERT DDL and DML ============

              CREATE TABLE contact
              (
              name_field VARCHAR (5) NOT NULL,
              address_field VARCHAR (20) NOT NULL,
              contact_age INTEGER NOT NULL
              );

              INSERT INTO contact
              VALUES
              ('Mary', 'address one', 25),
              ('Fred', 'address two', 35),
              ('Bill', 'address three', 47);






              share|improve this answer














              share|improve this answer



              share|improve this answer








              edited Dec 2 '17 at 13:53

























              answered Dec 2 '17 at 13:46









              VéraceVérace

              16.3k33550




              16.3k33550

























                  6














                  Converting a row to json



                  It doesn't sound to me like you want to aggregate JSON. You state you want the equivalent of row_to_json, if so then I suggest checking out the much simpler JSON_OBJECT



                  SELECT JSON_OBJECT(
                  'name_field', name_field,
                  'address_field', address_field,
                  'contact_age', contact_age
                  )
                  FROM contact;


                  Aggregating JSON



                  As a side note, if you do need to aggregate a resultset to json. then the upcoming MySQL 8 will do that for you.





                  • JSON_ARRAYAGG() Return result set as a single JSON array


                  • JSON_OBJECTAGG()` Return result set as a single JSON object






                  share|improve this answer






























                    6














                    Converting a row to json



                    It doesn't sound to me like you want to aggregate JSON. You state you want the equivalent of row_to_json, if so then I suggest checking out the much simpler JSON_OBJECT



                    SELECT JSON_OBJECT(
                    'name_field', name_field,
                    'address_field', address_field,
                    'contact_age', contact_age
                    )
                    FROM contact;


                    Aggregating JSON



                    As a side note, if you do need to aggregate a resultset to json. then the upcoming MySQL 8 will do that for you.





                    • JSON_ARRAYAGG() Return result set as a single JSON array


                    • JSON_OBJECTAGG()` Return result set as a single JSON object






                    share|improve this answer




























                      6












                      6








                      6







                      Converting a row to json



                      It doesn't sound to me like you want to aggregate JSON. You state you want the equivalent of row_to_json, if so then I suggest checking out the much simpler JSON_OBJECT



                      SELECT JSON_OBJECT(
                      'name_field', name_field,
                      'address_field', address_field,
                      'contact_age', contact_age
                      )
                      FROM contact;


                      Aggregating JSON



                      As a side note, if you do need to aggregate a resultset to json. then the upcoming MySQL 8 will do that for you.





                      • JSON_ARRAYAGG() Return result set as a single JSON array


                      • JSON_OBJECTAGG()` Return result set as a single JSON object






                      share|improve this answer















                      Converting a row to json



                      It doesn't sound to me like you want to aggregate JSON. You state you want the equivalent of row_to_json, if so then I suggest checking out the much simpler JSON_OBJECT



                      SELECT JSON_OBJECT(
                      'name_field', name_field,
                      'address_field', address_field,
                      'contact_age', contact_age
                      )
                      FROM contact;


                      Aggregating JSON



                      As a side note, if you do need to aggregate a resultset to json. then the upcoming MySQL 8 will do that for you.





                      • JSON_ARRAYAGG() Return result set as a single JSON array


                      • JSON_OBJECTAGG()` Return result set as a single JSON object







                      share|improve this answer














                      share|improve this answer



                      share|improve this answer








                      edited Oct 26 '18 at 14:57









                      John Rix

                      1033




                      1033










                      answered Dec 5 '17 at 7:23









                      Evan CarrollEvan Carroll

                      33.1k1074226




                      33.1k1074226























                          2














                          This will give you the same answer, but a lot easier code. I just used json_object with group_concat to simplify the other answer.



                          select 
                          concat('[',
                          GROUP_CONCAT(
                          JSON_OBJECT(
                          'name_field', name_field
                          ,'address_field', address_field
                          ,'contact_age', contact_age
                          )
                          SEPARATOR ',')
                          ,']')
                          from contact;





                          share|improve this answer






























                            2














                            This will give you the same answer, but a lot easier code. I just used json_object with group_concat to simplify the other answer.



                            select 
                            concat('[',
                            GROUP_CONCAT(
                            JSON_OBJECT(
                            'name_field', name_field
                            ,'address_field', address_field
                            ,'contact_age', contact_age
                            )
                            SEPARATOR ',')
                            ,']')
                            from contact;





                            share|improve this answer




























                              2












                              2








                              2







                              This will give you the same answer, but a lot easier code. I just used json_object with group_concat to simplify the other answer.



                              select 
                              concat('[',
                              GROUP_CONCAT(
                              JSON_OBJECT(
                              'name_field', name_field
                              ,'address_field', address_field
                              ,'contact_age', contact_age
                              )
                              SEPARATOR ',')
                              ,']')
                              from contact;





                              share|improve this answer















                              This will give you the same answer, but a lot easier code. I just used json_object with group_concat to simplify the other answer.



                              select 
                              concat('[',
                              GROUP_CONCAT(
                              JSON_OBJECT(
                              'name_field', name_field
                              ,'address_field', address_field
                              ,'contact_age', contact_age
                              )
                              SEPARATOR ',')
                              ,']')
                              from contact;






                              share|improve this answer














                              share|improve this answer



                              share|improve this answer








                              edited Feb 7 at 15:29









                              Paul White

                              53.6k14285458




                              53.6k14285458










                              answered Feb 7 at 15:23









                              dmeltdmelt

                              211




                              211























                                  0














                                  For an array of JSON objects (one object per row in query), you can do this:



                                  SELECT JSON_ARRAYAGG(JSON_OBJECT("fieldA", fieldA, "fieldB", fieldB)) 
                                  FROM table;


                                  It would result in a single JSON array containing all entries:



                                  [
                                  {
                                  "fieldA": "value",
                                  "fieldB": "value"
                                  },
                                  ...
                                  ]


                                  Unfortunately, MySQL does not allow for selecting all fields with *. This would be awesome, but does not work:



                                  SELECT JSON_ARRAYAGG(JSON_OBJECT(*)) FROM table;





                                  share|improve this answer








                                  New contributor




                                  Eneko Alonso is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
                                  Check out our Code of Conduct.

























                                    0














                                    For an array of JSON objects (one object per row in query), you can do this:



                                    SELECT JSON_ARRAYAGG(JSON_OBJECT("fieldA", fieldA, "fieldB", fieldB)) 
                                    FROM table;


                                    It would result in a single JSON array containing all entries:



                                    [
                                    {
                                    "fieldA": "value",
                                    "fieldB": "value"
                                    },
                                    ...
                                    ]


                                    Unfortunately, MySQL does not allow for selecting all fields with *. This would be awesome, but does not work:



                                    SELECT JSON_ARRAYAGG(JSON_OBJECT(*)) FROM table;





                                    share|improve this answer








                                    New contributor




                                    Eneko Alonso is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
                                    Check out our Code of Conduct.























                                      0












                                      0








                                      0







                                      For an array of JSON objects (one object per row in query), you can do this:



                                      SELECT JSON_ARRAYAGG(JSON_OBJECT("fieldA", fieldA, "fieldB", fieldB)) 
                                      FROM table;


                                      It would result in a single JSON array containing all entries:



                                      [
                                      {
                                      "fieldA": "value",
                                      "fieldB": "value"
                                      },
                                      ...
                                      ]


                                      Unfortunately, MySQL does not allow for selecting all fields with *. This would be awesome, but does not work:



                                      SELECT JSON_ARRAYAGG(JSON_OBJECT(*)) FROM table;





                                      share|improve this answer








                                      New contributor




                                      Eneko Alonso is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
                                      Check out our Code of Conduct.










                                      For an array of JSON objects (one object per row in query), you can do this:



                                      SELECT JSON_ARRAYAGG(JSON_OBJECT("fieldA", fieldA, "fieldB", fieldB)) 
                                      FROM table;


                                      It would result in a single JSON array containing all entries:



                                      [
                                      {
                                      "fieldA": "value",
                                      "fieldB": "value"
                                      },
                                      ...
                                      ]


                                      Unfortunately, MySQL does not allow for selecting all fields with *. This would be awesome, but does not work:



                                      SELECT JSON_ARRAYAGG(JSON_OBJECT(*)) FROM table;






                                      share|improve this answer








                                      New contributor




                                      Eneko Alonso is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
                                      Check out our Code of Conduct.









                                      share|improve this answer



                                      share|improve this answer






                                      New contributor




                                      Eneko Alonso is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
                                      Check out our Code of Conduct.









                                      answered 10 mins ago









                                      Eneko AlonsoEneko Alonso

                                      1012




                                      1012




                                      New contributor




                                      Eneko Alonso is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
                                      Check out our Code of Conduct.





                                      New contributor





                                      Eneko Alonso is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
                                      Check out our Code of Conduct.






                                      Eneko Alonso is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
                                      Check out our Code of Conduct.






























                                          draft saved

                                          draft discarded




















































                                          Thanks for contributing an answer to Database Administrators Stack Exchange!


                                          • Please be sure to answer the question. Provide details and share your research!

                                          But avoid



                                          • Asking for help, clarification, or responding to other answers.

                                          • Making statements based on opinion; back them up with references or personal experience.


                                          To learn more, see our tips on writing great answers.




                                          draft saved


                                          draft discarded














                                          StackExchange.ready(
                                          function () {
                                          StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fdba.stackexchange.com%2fquestions%2f192208%2fmysql-return-json-from-a-standard-sql-query%23new-answer', 'question_page');
                                          }
                                          );

                                          Post as a guest















                                          Required, but never shown





















































                                          Required, but never shown














                                          Required, but never shown












                                          Required, but never shown







                                          Required, but never shown

































                                          Required, but never shown














                                          Required, but never shown












                                          Required, but never shown







                                          Required, but never shown







                                          Popular posts from this blog

                                          Anexo:Material bélico de la Fuerza Aérea de Chile Índice Aeronaves Defensa...

                                          Always On Availability groups resolving state after failover - Remote harden of transaction...

                                          update json value to null Announcing the arrival of Valued Associate #679: Cesar Manara ...