jq print key and value for all in sub-objectBash - loop through files and pull JSON value from corresponding...

How can I find an old paper when the usual methods fail?

Do I have to cite common CS algorithms?

Can a bald person be a Nazir?

Who invented Monoid?

Can the IPA represent all languages' tones?

How to find directories containing only specific files

PhD advisor lost funding, need advice

How is являться different from есть and быть

Why is Python 2.7 still the default Python version in Ubuntu?

How would timezones work on a planet 100 times the size of our Earth

Why aren't rockets built with truss structures inside their fuel & oxidizer tanks to increase structural strength?

Are those flyers about apartment purchase a scam?

How big are the Choedan Kal?

Is there any way to stop a user from creating executables and running them?

Word for an event that will likely never happen again

Why aren’t there water shutoff valves for each room?

A torrent of foreign terms

Swap on SSD in 2019?

Case Condition for two lines

Why is the second S silent in "Sens dessus dessous"?

Telephone number in spoken words

How was the murder committed?

Clarification on Integrability

Should I email my professor about a recommendation letter if he has offered me a job?



jq print key and value for all in sub-object


Bash - loop through files and pull JSON value from corresponding keys in a master key filejq add or update a value with multiple --argCheck whether any value is zero using jq and return 0 to the calling shell scriptfind lines longer than X in JSON and delete the whole objectjq + how to print only the value of key under propertiesjq print value of an element where a key array is empty or a key is missingbash: assign variable and print to stdout in same commandGet values for a given key and its parent with jqConvert json file to a “key-path” with the resulting value at the end of each “key-path”Add bash variable as JSON key and value into object






.everyoneloves__top-leaderboard:empty,.everyoneloves__mid-leaderboard:empty,.everyoneloves__bot-mid-leaderboard:empty{ margin-bottom:0;
}







6















I found this Q/A with the solution to print all the keys in an object:



jq -r 'keys[] as $k | "($k), (.[$k] | .ip)"' 


In my case I want to perform the above but on a sub-object:



jq -r '.connections keys[] as $k | "($k), (.[$k] | .ip)"'


What is the proper syntax to do this?










share|improve this question































    6















    I found this Q/A with the solution to print all the keys in an object:



    jq -r 'keys[] as $k | "($k), (.[$k] | .ip)"' 


    In my case I want to perform the above but on a sub-object:



    jq -r '.connections keys[] as $k | "($k), (.[$k] | .ip)"'


    What is the proper syntax to do this?










    share|improve this question



























      6












      6








      6


      3






      I found this Q/A with the solution to print all the keys in an object:



      jq -r 'keys[] as $k | "($k), (.[$k] | .ip)"' 


      In my case I want to perform the above but on a sub-object:



      jq -r '.connections keys[] as $k | "($k), (.[$k] | .ip)"'


      What is the proper syntax to do this?










      share|improve this question














      I found this Q/A with the solution to print all the keys in an object:



      jq -r 'keys[] as $k | "($k), (.[$k] | .ip)"' 


      In my case I want to perform the above but on a sub-object:



      jq -r '.connections keys[] as $k | "($k), (.[$k] | .ip)"'


      What is the proper syntax to do this?







      json jq






      share|improve this question













      share|improve this question











      share|improve this question




      share|improve this question










      asked Nov 22 '17 at 21:53









      Philip KirkbridePhilip Kirkbride

      2,9066 gold badges46 silver badges106 bronze badges




      2,9066 gold badges46 silver badges106 bronze badges

























          2 Answers
          2






          active

          oldest

          votes


















          14














          Simply pipe to keys function:



          Sample input.json:



          {
          "connections": {
          "host1": { "ip": "10.1.2.3" },
          "host2": { "ip": "10.1.2.2" },
          "host3": { "ip": "10.1.18.1" }
          }
          }




          jq -r '.connections | keys[] as $k | "($k), (.[$k] | .ip)"' input.json


          The output:



          host1, 10.1.2.3
          host2, 10.1.2.2
          host3, 10.1.18.1





          share|improve this answer





















          • 3





            keys sorts the keys, so it is worth pointing out that keys_unsorted does not.

            – peak
            Jan 7 '18 at 13:11











          • @peak, the OP wrote "I found this stackoverflow.com/questions/34226370/… ..." where the accepted answer clearly says "keys produces the key names in sorted order; if you want them in the original order, use keys_unsorted". So the OP is aware about that and have chosen keys consciously.

            – RomanPerekhrest
            Jan 7 '18 at 14:23








          • 1





            The comment was meant for others coming across this Q&A.

            – peak
            Jan 7 '18 at 15:06





















          0














          A more generic bash function to export vars ( with interpolation ):



          #
          #------------------------------------------------------------------------------
          # usage example:
          # doExportJsonSectionVars cnf/env/dev.env.json '.env.virtual.docker.spark_base'
          #------------------------------------------------------------------------------
          doExportJsonSectionVars(){

          json_file="$1"
          shift 1;
          test -f "$json_file" || echo "the json_file: $json_file does not exist !!! Nothing to do" && exit 1

          section="$1"
          test -z "$section" && echo "the section in doExportJsonSectionVars is empty !!! nothing to do !!!" && exit 1
          shift 1;

          while read -r l ; do
          eval $l ;
          done < <(cat "$json_file"| jq -r "$section"'|keys_unsorted[] as $key|"export ($key)=(.[$key])"')
          }


          example data



          cat cnf/env/dev.env.json
          {
          "env": {
          "ENV_TYPE": "dev",
          "physical": {
          "var_name": "var_value"
          },
          "virtual": {
          "docker": {
          "spark_base": {
          "SPARK_HOME": "/opt/spark"
          , "SPARK_CONF": "$SPARK_HOME/conf"
          }
          , "spark_master": {
          "var_name": "var_value"
          }
          , "spark_worker": {
          "var_name": "var_value"
          }
          }
          , "var_name": "var_value"
          }
          }
          }





          share|improve this answer




























            Your Answer








            StackExchange.ready(function() {
            var channelOptions = {
            tags: "".split(" "),
            id: "106"
            };
            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%2funix.stackexchange.com%2fquestions%2f406410%2fjq-print-key-and-value-for-all-in-sub-object%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









            14














            Simply pipe to keys function:



            Sample input.json:



            {
            "connections": {
            "host1": { "ip": "10.1.2.3" },
            "host2": { "ip": "10.1.2.2" },
            "host3": { "ip": "10.1.18.1" }
            }
            }




            jq -r '.connections | keys[] as $k | "($k), (.[$k] | .ip)"' input.json


            The output:



            host1, 10.1.2.3
            host2, 10.1.2.2
            host3, 10.1.18.1





            share|improve this answer





















            • 3





              keys sorts the keys, so it is worth pointing out that keys_unsorted does not.

              – peak
              Jan 7 '18 at 13:11











            • @peak, the OP wrote "I found this stackoverflow.com/questions/34226370/… ..." where the accepted answer clearly says "keys produces the key names in sorted order; if you want them in the original order, use keys_unsorted". So the OP is aware about that and have chosen keys consciously.

              – RomanPerekhrest
              Jan 7 '18 at 14:23








            • 1





              The comment was meant for others coming across this Q&A.

              – peak
              Jan 7 '18 at 15:06


















            14














            Simply pipe to keys function:



            Sample input.json:



            {
            "connections": {
            "host1": { "ip": "10.1.2.3" },
            "host2": { "ip": "10.1.2.2" },
            "host3": { "ip": "10.1.18.1" }
            }
            }




            jq -r '.connections | keys[] as $k | "($k), (.[$k] | .ip)"' input.json


            The output:



            host1, 10.1.2.3
            host2, 10.1.2.2
            host3, 10.1.18.1





            share|improve this answer





















            • 3





              keys sorts the keys, so it is worth pointing out that keys_unsorted does not.

              – peak
              Jan 7 '18 at 13:11











            • @peak, the OP wrote "I found this stackoverflow.com/questions/34226370/… ..." where the accepted answer clearly says "keys produces the key names in sorted order; if you want them in the original order, use keys_unsorted". So the OP is aware about that and have chosen keys consciously.

              – RomanPerekhrest
              Jan 7 '18 at 14:23








            • 1





              The comment was meant for others coming across this Q&A.

              – peak
              Jan 7 '18 at 15:06
















            14












            14








            14







            Simply pipe to keys function:



            Sample input.json:



            {
            "connections": {
            "host1": { "ip": "10.1.2.3" },
            "host2": { "ip": "10.1.2.2" },
            "host3": { "ip": "10.1.18.1" }
            }
            }




            jq -r '.connections | keys[] as $k | "($k), (.[$k] | .ip)"' input.json


            The output:



            host1, 10.1.2.3
            host2, 10.1.2.2
            host3, 10.1.18.1





            share|improve this answer













            Simply pipe to keys function:



            Sample input.json:



            {
            "connections": {
            "host1": { "ip": "10.1.2.3" },
            "host2": { "ip": "10.1.2.2" },
            "host3": { "ip": "10.1.18.1" }
            }
            }




            jq -r '.connections | keys[] as $k | "($k), (.[$k] | .ip)"' input.json


            The output:



            host1, 10.1.2.3
            host2, 10.1.2.2
            host3, 10.1.18.1






            share|improve this answer












            share|improve this answer



            share|improve this answer










            answered Nov 22 '17 at 23:12









            RomanPerekhrestRomanPerekhrest

            23.9k1 gold badge28 silver badges51 bronze badges




            23.9k1 gold badge28 silver badges51 bronze badges











            • 3





              keys sorts the keys, so it is worth pointing out that keys_unsorted does not.

              – peak
              Jan 7 '18 at 13:11











            • @peak, the OP wrote "I found this stackoverflow.com/questions/34226370/… ..." where the accepted answer clearly says "keys produces the key names in sorted order; if you want them in the original order, use keys_unsorted". So the OP is aware about that and have chosen keys consciously.

              – RomanPerekhrest
              Jan 7 '18 at 14:23








            • 1





              The comment was meant for others coming across this Q&A.

              – peak
              Jan 7 '18 at 15:06
















            • 3





              keys sorts the keys, so it is worth pointing out that keys_unsorted does not.

              – peak
              Jan 7 '18 at 13:11











            • @peak, the OP wrote "I found this stackoverflow.com/questions/34226370/… ..." where the accepted answer clearly says "keys produces the key names in sorted order; if you want them in the original order, use keys_unsorted". So the OP is aware about that and have chosen keys consciously.

              – RomanPerekhrest
              Jan 7 '18 at 14:23








            • 1





              The comment was meant for others coming across this Q&A.

              – peak
              Jan 7 '18 at 15:06










            3




            3





            keys sorts the keys, so it is worth pointing out that keys_unsorted does not.

            – peak
            Jan 7 '18 at 13:11





            keys sorts the keys, so it is worth pointing out that keys_unsorted does not.

            – peak
            Jan 7 '18 at 13:11













            @peak, the OP wrote "I found this stackoverflow.com/questions/34226370/… ..." where the accepted answer clearly says "keys produces the key names in sorted order; if you want them in the original order, use keys_unsorted". So the OP is aware about that and have chosen keys consciously.

            – RomanPerekhrest
            Jan 7 '18 at 14:23







            @peak, the OP wrote "I found this stackoverflow.com/questions/34226370/… ..." where the accepted answer clearly says "keys produces the key names in sorted order; if you want them in the original order, use keys_unsorted". So the OP is aware about that and have chosen keys consciously.

            – RomanPerekhrest
            Jan 7 '18 at 14:23






            1




            1





            The comment was meant for others coming across this Q&A.

            – peak
            Jan 7 '18 at 15:06







            The comment was meant for others coming across this Q&A.

            – peak
            Jan 7 '18 at 15:06















            0














            A more generic bash function to export vars ( with interpolation ):



            #
            #------------------------------------------------------------------------------
            # usage example:
            # doExportJsonSectionVars cnf/env/dev.env.json '.env.virtual.docker.spark_base'
            #------------------------------------------------------------------------------
            doExportJsonSectionVars(){

            json_file="$1"
            shift 1;
            test -f "$json_file" || echo "the json_file: $json_file does not exist !!! Nothing to do" && exit 1

            section="$1"
            test -z "$section" && echo "the section in doExportJsonSectionVars is empty !!! nothing to do !!!" && exit 1
            shift 1;

            while read -r l ; do
            eval $l ;
            done < <(cat "$json_file"| jq -r "$section"'|keys_unsorted[] as $key|"export ($key)=(.[$key])"')
            }


            example data



            cat cnf/env/dev.env.json
            {
            "env": {
            "ENV_TYPE": "dev",
            "physical": {
            "var_name": "var_value"
            },
            "virtual": {
            "docker": {
            "spark_base": {
            "SPARK_HOME": "/opt/spark"
            , "SPARK_CONF": "$SPARK_HOME/conf"
            }
            , "spark_master": {
            "var_name": "var_value"
            }
            , "spark_worker": {
            "var_name": "var_value"
            }
            }
            , "var_name": "var_value"
            }
            }
            }





            share|improve this answer






























              0














              A more generic bash function to export vars ( with interpolation ):



              #
              #------------------------------------------------------------------------------
              # usage example:
              # doExportJsonSectionVars cnf/env/dev.env.json '.env.virtual.docker.spark_base'
              #------------------------------------------------------------------------------
              doExportJsonSectionVars(){

              json_file="$1"
              shift 1;
              test -f "$json_file" || echo "the json_file: $json_file does not exist !!! Nothing to do" && exit 1

              section="$1"
              test -z "$section" && echo "the section in doExportJsonSectionVars is empty !!! nothing to do !!!" && exit 1
              shift 1;

              while read -r l ; do
              eval $l ;
              done < <(cat "$json_file"| jq -r "$section"'|keys_unsorted[] as $key|"export ($key)=(.[$key])"')
              }


              example data



              cat cnf/env/dev.env.json
              {
              "env": {
              "ENV_TYPE": "dev",
              "physical": {
              "var_name": "var_value"
              },
              "virtual": {
              "docker": {
              "spark_base": {
              "SPARK_HOME": "/opt/spark"
              , "SPARK_CONF": "$SPARK_HOME/conf"
              }
              , "spark_master": {
              "var_name": "var_value"
              }
              , "spark_worker": {
              "var_name": "var_value"
              }
              }
              , "var_name": "var_value"
              }
              }
              }





              share|improve this answer




























                0












                0








                0







                A more generic bash function to export vars ( with interpolation ):



                #
                #------------------------------------------------------------------------------
                # usage example:
                # doExportJsonSectionVars cnf/env/dev.env.json '.env.virtual.docker.spark_base'
                #------------------------------------------------------------------------------
                doExportJsonSectionVars(){

                json_file="$1"
                shift 1;
                test -f "$json_file" || echo "the json_file: $json_file does not exist !!! Nothing to do" && exit 1

                section="$1"
                test -z "$section" && echo "the section in doExportJsonSectionVars is empty !!! nothing to do !!!" && exit 1
                shift 1;

                while read -r l ; do
                eval $l ;
                done < <(cat "$json_file"| jq -r "$section"'|keys_unsorted[] as $key|"export ($key)=(.[$key])"')
                }


                example data



                cat cnf/env/dev.env.json
                {
                "env": {
                "ENV_TYPE": "dev",
                "physical": {
                "var_name": "var_value"
                },
                "virtual": {
                "docker": {
                "spark_base": {
                "SPARK_HOME": "/opt/spark"
                , "SPARK_CONF": "$SPARK_HOME/conf"
                }
                , "spark_master": {
                "var_name": "var_value"
                }
                , "spark_worker": {
                "var_name": "var_value"
                }
                }
                , "var_name": "var_value"
                }
                }
                }





                share|improve this answer













                A more generic bash function to export vars ( with interpolation ):



                #
                #------------------------------------------------------------------------------
                # usage example:
                # doExportJsonSectionVars cnf/env/dev.env.json '.env.virtual.docker.spark_base'
                #------------------------------------------------------------------------------
                doExportJsonSectionVars(){

                json_file="$1"
                shift 1;
                test -f "$json_file" || echo "the json_file: $json_file does not exist !!! Nothing to do" && exit 1

                section="$1"
                test -z "$section" && echo "the section in doExportJsonSectionVars is empty !!! nothing to do !!!" && exit 1
                shift 1;

                while read -r l ; do
                eval $l ;
                done < <(cat "$json_file"| jq -r "$section"'|keys_unsorted[] as $key|"export ($key)=(.[$key])"')
                }


                example data



                cat cnf/env/dev.env.json
                {
                "env": {
                "ENV_TYPE": "dev",
                "physical": {
                "var_name": "var_value"
                },
                "virtual": {
                "docker": {
                "spark_base": {
                "SPARK_HOME": "/opt/spark"
                , "SPARK_CONF": "$SPARK_HOME/conf"
                }
                , "spark_master": {
                "var_name": "var_value"
                }
                , "spark_worker": {
                "var_name": "var_value"
                }
                }
                , "var_name": "var_value"
                }
                }
                }






                share|improve this answer












                share|improve this answer



                share|improve this answer










                answered 16 hours ago









                Yordan GeorgievYordan Georgiev

                1614 bronze badges




                1614 bronze badges

































                    draft saved

                    draft discarded




















































                    Thanks for contributing an answer to Unix & Linux 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%2funix.stackexchange.com%2fquestions%2f406410%2fjq-print-key-and-value-for-all-in-sub-object%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

                    Taj Mahal Inhaltsverzeichnis Aufbau | Geschichte | 350-Jahr-Feier | Heutige Bedeutung | Siehe auch |...

                    Baia Sprie Cuprins Etimologie | Istorie | Demografie | Politică și administrație | Arii naturale...

                    Nicolae Petrescu-Găină Cuprins Biografie | Opera | In memoriam | Varia | Controverse, incertitudini...