MySQL Update or Rename a Key in JSON












3















I'm having this json stored in db



{"endDate": "2018-10-10", "startDate": "2017-09-05", "oldKeyValue": {"foo": 1000, "bar": 2000, "baz": 3000}, "anotherValue": 0}


How can I rename "oldKeyValue" key to "newKeyValue" without knowing the index of the key in an UPDATE query? I'm looking for something like this



UPDATE `my_table` SET `my_col` = JSON()


NOTE: only the key needs to change, the values (i.e. {"foo": 1000, "bar": 2000, "baz": 3000}) should remain the same










share|improve this question

























  • What type does column have?

    – Maxim Fedorov
    Nov 22 '18 at 14:43











  • Without parsing it out to a table, selecting it as something else and reserializing it to json, the easiest way (if it's stored as a string) is gonna be update table set jsoncolumn = REPLACE(jsoncolumn, '"oldKeyValue":', '"newKeyValue":') - it should work out because json's structure should be relatively regular, i.e. a string surrounded by quotes and followed by colon should be a key, as it would have to be escaped to be part of a string value

    – Caius Jard
    Nov 22 '18 at 14:43


















3















I'm having this json stored in db



{"endDate": "2018-10-10", "startDate": "2017-09-05", "oldKeyValue": {"foo": 1000, "bar": 2000, "baz": 3000}, "anotherValue": 0}


How can I rename "oldKeyValue" key to "newKeyValue" without knowing the index of the key in an UPDATE query? I'm looking for something like this



UPDATE `my_table` SET `my_col` = JSON()


NOTE: only the key needs to change, the values (i.e. {"foo": 1000, "bar": 2000, "baz": 3000}) should remain the same










share|improve this question

























  • What type does column have?

    – Maxim Fedorov
    Nov 22 '18 at 14:43











  • Without parsing it out to a table, selecting it as something else and reserializing it to json, the easiest way (if it's stored as a string) is gonna be update table set jsoncolumn = REPLACE(jsoncolumn, '"oldKeyValue":', '"newKeyValue":') - it should work out because json's structure should be relatively regular, i.e. a string surrounded by quotes and followed by colon should be a key, as it would have to be escaped to be part of a string value

    – Caius Jard
    Nov 22 '18 at 14:43
















3












3








3








I'm having this json stored in db



{"endDate": "2018-10-10", "startDate": "2017-09-05", "oldKeyValue": {"foo": 1000, "bar": 2000, "baz": 3000}, "anotherValue": 0}


How can I rename "oldKeyValue" key to "newKeyValue" without knowing the index of the key in an UPDATE query? I'm looking for something like this



UPDATE `my_table` SET `my_col` = JSON()


NOTE: only the key needs to change, the values (i.e. {"foo": 1000, "bar": 2000, "baz": 3000}) should remain the same










share|improve this question
















I'm having this json stored in db



{"endDate": "2018-10-10", "startDate": "2017-09-05", "oldKeyValue": {"foo": 1000, "bar": 2000, "baz": 3000}, "anotherValue": 0}


How can I rename "oldKeyValue" key to "newKeyValue" without knowing the index of the key in an UPDATE query? I'm looking for something like this



UPDATE `my_table` SET `my_col` = JSON()


NOTE: only the key needs to change, the values (i.e. {"foo": 1000, "bar": 2000, "baz": 3000}) should remain the same







mysql json






share|improve this question















share|improve this question













share|improve this question




share|improve this question








edited Nov 22 '18 at 15:13









Madhur Bhaiya

19.6k62236




19.6k62236










asked Nov 22 '18 at 14:39









LykosLykos

1,39493570




1,39493570













  • What type does column have?

    – Maxim Fedorov
    Nov 22 '18 at 14:43











  • Without parsing it out to a table, selecting it as something else and reserializing it to json, the easiest way (if it's stored as a string) is gonna be update table set jsoncolumn = REPLACE(jsoncolumn, '"oldKeyValue":', '"newKeyValue":') - it should work out because json's structure should be relatively regular, i.e. a string surrounded by quotes and followed by colon should be a key, as it would have to be escaped to be part of a string value

    – Caius Jard
    Nov 22 '18 at 14:43





















  • What type does column have?

    – Maxim Fedorov
    Nov 22 '18 at 14:43











  • Without parsing it out to a table, selecting it as something else and reserializing it to json, the easiest way (if it's stored as a string) is gonna be update table set jsoncolumn = REPLACE(jsoncolumn, '"oldKeyValue":', '"newKeyValue":') - it should work out because json's structure should be relatively regular, i.e. a string surrounded by quotes and followed by colon should be a key, as it would have to be escaped to be part of a string value

    – Caius Jard
    Nov 22 '18 at 14:43



















What type does column have?

– Maxim Fedorov
Nov 22 '18 at 14:43





What type does column have?

– Maxim Fedorov
Nov 22 '18 at 14:43













Without parsing it out to a table, selecting it as something else and reserializing it to json, the easiest way (if it's stored as a string) is gonna be update table set jsoncolumn = REPLACE(jsoncolumn, '"oldKeyValue":', '"newKeyValue":') - it should work out because json's structure should be relatively regular, i.e. a string surrounded by quotes and followed by colon should be a key, as it would have to be escaped to be part of a string value

– Caius Jard
Nov 22 '18 at 14:43







Without parsing it out to a table, selecting it as something else and reserializing it to json, the easiest way (if it's stored as a string) is gonna be update table set jsoncolumn = REPLACE(jsoncolumn, '"oldKeyValue":', '"newKeyValue":') - it should work out because json's structure should be relatively regular, i.e. a string surrounded by quotes and followed by colon should be a key, as it would have to be escaped to be part of a string value

– Caius Jard
Nov 22 '18 at 14:43














2 Answers
2






active

oldest

votes


















2














There is no straightforward JSON function to do the same. We can use a combination of some JSON functions.



We will remove the oldKey-oldValue pair using Json_Remove() function, and then Json_Insert() the newKey-oldValue pair.



Json_Extract() function is used to fetch value corresponding to an input key in the JSON document.



UPDATE `my_table` 
SET `my_col` = JSON_INSERT(
JSON_REMOVE(my_col, '$.oldKeyValue'),
'$.newKeyValue',
JSON_EXTRACT(my_col, '$.oldKeyValue')
);


Demo



SET @my_col := '{"endDate": "2018-10-10", "startDate": "2017-09-05", "oldKeyValue": {"foo": 1000, "bar": 2000, "baz": 3000}, "anotherValue": 0}';

SET @new_col := JSON_INSERT(
JSON_REMOVE(@my_col, '$.oldKeyValue'),
'$.newKeyValue',
JSON_EXTRACT(@my_col,'$.oldKeyValue')
);

SELECT @new_col;


Result



| @new_col                                                                                                                        |
| ------------------------------------------------------------------------------------------------------------------------------- |
| {"endDate": "2018-10-10", "startDate": "2017-09-05", "newKeyValue": {"bar": 2000, "baz": 3000, "foo": 1000}, "anotherValue": 0} |




As an alternative to Json_Extract(), we can also use -> operator to access the Value corresponding to a given Key in the JSON doc.



UPDATE `my_table` 
SET `my_col` = JSON_INSERT(
JSON_REMOVE(my_col, '$.oldKeyValue'),
'$.newKeyValue',
my_col->'$.oldKeyValue'
);





share|improve this answer





















  • 1





    Beat me to it +1. I agree that there is no direct function. So it's either this, or taking a chance on a plain replacement.

    – Tim Biegeleisen
    Nov 22 '18 at 14:57











  • I noticed you change your script. I tried the first one using JSON_INSERT and JSON_REMOVE. Perhaps its better to keep this too along with JSON_EXTRACT in your answer to avoid confusion

    – Lykos
    Nov 22 '18 at 15:15











  • @Lykos I will; it was not working on fiddle due to some parsing issues at fiddle end. I will update the answer with that also, once i get a fiddle working for it.

    – Madhur Bhaiya
    Nov 22 '18 at 15:16



















0














I personally prefer another method:



UPDATE my_table SET my_col = REPLACE(my_col, '"oldKeyValue":', '"newKeyValue":')


This replaces directly the key name in the JSON string without destroying the JSON structure.



I am using the additional : in order to avoid an unintentional replacement in a value.






share|improve this answer























    Your Answer






    StackExchange.ifUsing("editor", function () {
    StackExchange.using("externalEditor", function () {
    StackExchange.using("snippets", function () {
    StackExchange.snippets.init();
    });
    });
    }, "code-snippets");

    StackExchange.ready(function() {
    var channelOptions = {
    tags: "".split(" "),
    id: "1"
    };
    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: true,
    noModals: true,
    showLowRepImageUploadWarning: true,
    reputationToPostImages: 10,
    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%2fstackoverflow.com%2fquestions%2f53433285%2fmysql-update-or-rename-a-key-in-json%23new-answer', 'question_page');
    }
    );

    Post as a guest















    Required, but never shown

























    2 Answers
    2






    active

    oldest

    votes








    2 Answers
    2






    active

    oldest

    votes









    active

    oldest

    votes






    active

    oldest

    votes









    2














    There is no straightforward JSON function to do the same. We can use a combination of some JSON functions.



    We will remove the oldKey-oldValue pair using Json_Remove() function, and then Json_Insert() the newKey-oldValue pair.



    Json_Extract() function is used to fetch value corresponding to an input key in the JSON document.



    UPDATE `my_table` 
    SET `my_col` = JSON_INSERT(
    JSON_REMOVE(my_col, '$.oldKeyValue'),
    '$.newKeyValue',
    JSON_EXTRACT(my_col, '$.oldKeyValue')
    );


    Demo



    SET @my_col := '{"endDate": "2018-10-10", "startDate": "2017-09-05", "oldKeyValue": {"foo": 1000, "bar": 2000, "baz": 3000}, "anotherValue": 0}';

    SET @new_col := JSON_INSERT(
    JSON_REMOVE(@my_col, '$.oldKeyValue'),
    '$.newKeyValue',
    JSON_EXTRACT(@my_col,'$.oldKeyValue')
    );

    SELECT @new_col;


    Result



    | @new_col                                                                                                                        |
    | ------------------------------------------------------------------------------------------------------------------------------- |
    | {"endDate": "2018-10-10", "startDate": "2017-09-05", "newKeyValue": {"bar": 2000, "baz": 3000, "foo": 1000}, "anotherValue": 0} |




    As an alternative to Json_Extract(), we can also use -> operator to access the Value corresponding to a given Key in the JSON doc.



    UPDATE `my_table` 
    SET `my_col` = JSON_INSERT(
    JSON_REMOVE(my_col, '$.oldKeyValue'),
    '$.newKeyValue',
    my_col->'$.oldKeyValue'
    );





    share|improve this answer





















    • 1





      Beat me to it +1. I agree that there is no direct function. So it's either this, or taking a chance on a plain replacement.

      – Tim Biegeleisen
      Nov 22 '18 at 14:57











    • I noticed you change your script. I tried the first one using JSON_INSERT and JSON_REMOVE. Perhaps its better to keep this too along with JSON_EXTRACT in your answer to avoid confusion

      – Lykos
      Nov 22 '18 at 15:15











    • @Lykos I will; it was not working on fiddle due to some parsing issues at fiddle end. I will update the answer with that also, once i get a fiddle working for it.

      – Madhur Bhaiya
      Nov 22 '18 at 15:16
















    2














    There is no straightforward JSON function to do the same. We can use a combination of some JSON functions.



    We will remove the oldKey-oldValue pair using Json_Remove() function, and then Json_Insert() the newKey-oldValue pair.



    Json_Extract() function is used to fetch value corresponding to an input key in the JSON document.



    UPDATE `my_table` 
    SET `my_col` = JSON_INSERT(
    JSON_REMOVE(my_col, '$.oldKeyValue'),
    '$.newKeyValue',
    JSON_EXTRACT(my_col, '$.oldKeyValue')
    );


    Demo



    SET @my_col := '{"endDate": "2018-10-10", "startDate": "2017-09-05", "oldKeyValue": {"foo": 1000, "bar": 2000, "baz": 3000}, "anotherValue": 0}';

    SET @new_col := JSON_INSERT(
    JSON_REMOVE(@my_col, '$.oldKeyValue'),
    '$.newKeyValue',
    JSON_EXTRACT(@my_col,'$.oldKeyValue')
    );

    SELECT @new_col;


    Result



    | @new_col                                                                                                                        |
    | ------------------------------------------------------------------------------------------------------------------------------- |
    | {"endDate": "2018-10-10", "startDate": "2017-09-05", "newKeyValue": {"bar": 2000, "baz": 3000, "foo": 1000}, "anotherValue": 0} |




    As an alternative to Json_Extract(), we can also use -> operator to access the Value corresponding to a given Key in the JSON doc.



    UPDATE `my_table` 
    SET `my_col` = JSON_INSERT(
    JSON_REMOVE(my_col, '$.oldKeyValue'),
    '$.newKeyValue',
    my_col->'$.oldKeyValue'
    );





    share|improve this answer





















    • 1





      Beat me to it +1. I agree that there is no direct function. So it's either this, or taking a chance on a plain replacement.

      – Tim Biegeleisen
      Nov 22 '18 at 14:57











    • I noticed you change your script. I tried the first one using JSON_INSERT and JSON_REMOVE. Perhaps its better to keep this too along with JSON_EXTRACT in your answer to avoid confusion

      – Lykos
      Nov 22 '18 at 15:15











    • @Lykos I will; it was not working on fiddle due to some parsing issues at fiddle end. I will update the answer with that also, once i get a fiddle working for it.

      – Madhur Bhaiya
      Nov 22 '18 at 15:16














    2












    2








    2







    There is no straightforward JSON function to do the same. We can use a combination of some JSON functions.



    We will remove the oldKey-oldValue pair using Json_Remove() function, and then Json_Insert() the newKey-oldValue pair.



    Json_Extract() function is used to fetch value corresponding to an input key in the JSON document.



    UPDATE `my_table` 
    SET `my_col` = JSON_INSERT(
    JSON_REMOVE(my_col, '$.oldKeyValue'),
    '$.newKeyValue',
    JSON_EXTRACT(my_col, '$.oldKeyValue')
    );


    Demo



    SET @my_col := '{"endDate": "2018-10-10", "startDate": "2017-09-05", "oldKeyValue": {"foo": 1000, "bar": 2000, "baz": 3000}, "anotherValue": 0}';

    SET @new_col := JSON_INSERT(
    JSON_REMOVE(@my_col, '$.oldKeyValue'),
    '$.newKeyValue',
    JSON_EXTRACT(@my_col,'$.oldKeyValue')
    );

    SELECT @new_col;


    Result



    | @new_col                                                                                                                        |
    | ------------------------------------------------------------------------------------------------------------------------------- |
    | {"endDate": "2018-10-10", "startDate": "2017-09-05", "newKeyValue": {"bar": 2000, "baz": 3000, "foo": 1000}, "anotherValue": 0} |




    As an alternative to Json_Extract(), we can also use -> operator to access the Value corresponding to a given Key in the JSON doc.



    UPDATE `my_table` 
    SET `my_col` = JSON_INSERT(
    JSON_REMOVE(my_col, '$.oldKeyValue'),
    '$.newKeyValue',
    my_col->'$.oldKeyValue'
    );





    share|improve this answer















    There is no straightforward JSON function to do the same. We can use a combination of some JSON functions.



    We will remove the oldKey-oldValue pair using Json_Remove() function, and then Json_Insert() the newKey-oldValue pair.



    Json_Extract() function is used to fetch value corresponding to an input key in the JSON document.



    UPDATE `my_table` 
    SET `my_col` = JSON_INSERT(
    JSON_REMOVE(my_col, '$.oldKeyValue'),
    '$.newKeyValue',
    JSON_EXTRACT(my_col, '$.oldKeyValue')
    );


    Demo



    SET @my_col := '{"endDate": "2018-10-10", "startDate": "2017-09-05", "oldKeyValue": {"foo": 1000, "bar": 2000, "baz": 3000}, "anotherValue": 0}';

    SET @new_col := JSON_INSERT(
    JSON_REMOVE(@my_col, '$.oldKeyValue'),
    '$.newKeyValue',
    JSON_EXTRACT(@my_col,'$.oldKeyValue')
    );

    SELECT @new_col;


    Result



    | @new_col                                                                                                                        |
    | ------------------------------------------------------------------------------------------------------------------------------- |
    | {"endDate": "2018-10-10", "startDate": "2017-09-05", "newKeyValue": {"bar": 2000, "baz": 3000, "foo": 1000}, "anotherValue": 0} |




    As an alternative to Json_Extract(), we can also use -> operator to access the Value corresponding to a given Key in the JSON doc.



    UPDATE `my_table` 
    SET `my_col` = JSON_INSERT(
    JSON_REMOVE(my_col, '$.oldKeyValue'),
    '$.newKeyValue',
    my_col->'$.oldKeyValue'
    );






    share|improve this answer














    share|improve this answer



    share|improve this answer








    edited Nov 22 '18 at 16:34

























    answered Nov 22 '18 at 14:56









    Madhur BhaiyaMadhur Bhaiya

    19.6k62236




    19.6k62236








    • 1





      Beat me to it +1. I agree that there is no direct function. So it's either this, or taking a chance on a plain replacement.

      – Tim Biegeleisen
      Nov 22 '18 at 14:57











    • I noticed you change your script. I tried the first one using JSON_INSERT and JSON_REMOVE. Perhaps its better to keep this too along with JSON_EXTRACT in your answer to avoid confusion

      – Lykos
      Nov 22 '18 at 15:15











    • @Lykos I will; it was not working on fiddle due to some parsing issues at fiddle end. I will update the answer with that also, once i get a fiddle working for it.

      – Madhur Bhaiya
      Nov 22 '18 at 15:16














    • 1





      Beat me to it +1. I agree that there is no direct function. So it's either this, or taking a chance on a plain replacement.

      – Tim Biegeleisen
      Nov 22 '18 at 14:57











    • I noticed you change your script. I tried the first one using JSON_INSERT and JSON_REMOVE. Perhaps its better to keep this too along with JSON_EXTRACT in your answer to avoid confusion

      – Lykos
      Nov 22 '18 at 15:15











    • @Lykos I will; it was not working on fiddle due to some parsing issues at fiddle end. I will update the answer with that also, once i get a fiddle working for it.

      – Madhur Bhaiya
      Nov 22 '18 at 15:16








    1




    1





    Beat me to it +1. I agree that there is no direct function. So it's either this, or taking a chance on a plain replacement.

    – Tim Biegeleisen
    Nov 22 '18 at 14:57





    Beat me to it +1. I agree that there is no direct function. So it's either this, or taking a chance on a plain replacement.

    – Tim Biegeleisen
    Nov 22 '18 at 14:57













    I noticed you change your script. I tried the first one using JSON_INSERT and JSON_REMOVE. Perhaps its better to keep this too along with JSON_EXTRACT in your answer to avoid confusion

    – Lykos
    Nov 22 '18 at 15:15





    I noticed you change your script. I tried the first one using JSON_INSERT and JSON_REMOVE. Perhaps its better to keep this too along with JSON_EXTRACT in your answer to avoid confusion

    – Lykos
    Nov 22 '18 at 15:15













    @Lykos I will; it was not working on fiddle due to some parsing issues at fiddle end. I will update the answer with that also, once i get a fiddle working for it.

    – Madhur Bhaiya
    Nov 22 '18 at 15:16





    @Lykos I will; it was not working on fiddle due to some parsing issues at fiddle end. I will update the answer with that also, once i get a fiddle working for it.

    – Madhur Bhaiya
    Nov 22 '18 at 15:16













    0














    I personally prefer another method:



    UPDATE my_table SET my_col = REPLACE(my_col, '"oldKeyValue":', '"newKeyValue":')


    This replaces directly the key name in the JSON string without destroying the JSON structure.



    I am using the additional : in order to avoid an unintentional replacement in a value.






    share|improve this answer




























      0














      I personally prefer another method:



      UPDATE my_table SET my_col = REPLACE(my_col, '"oldKeyValue":', '"newKeyValue":')


      This replaces directly the key name in the JSON string without destroying the JSON structure.



      I am using the additional : in order to avoid an unintentional replacement in a value.






      share|improve this answer


























        0












        0








        0







        I personally prefer another method:



        UPDATE my_table SET my_col = REPLACE(my_col, '"oldKeyValue":', '"newKeyValue":')


        This replaces directly the key name in the JSON string without destroying the JSON structure.



        I am using the additional : in order to avoid an unintentional replacement in a value.






        share|improve this answer













        I personally prefer another method:



        UPDATE my_table SET my_col = REPLACE(my_col, '"oldKeyValue":', '"newKeyValue":')


        This replaces directly the key name in the JSON string without destroying the JSON structure.



        I am using the additional : in order to avoid an unintentional replacement in a value.







        share|improve this answer












        share|improve this answer



        share|improve this answer










        answered Jan 17 at 17:53









        Al BundyAl Bundy

        2,18921641




        2,18921641






























            draft saved

            draft discarded




















































            Thanks for contributing an answer to Stack Overflow!


            • 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%2fstackoverflow.com%2fquestions%2f53433285%2fmysql-update-or-rename-a-key-in-json%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

            Create new schema in PostgreSQL using DBeaver

            Deepest pit of an array with Javascript: test on Codility

            Fotorealismo