How to extract specific fields recursively from json output?How do I format a Microsoft JSON date?How can I pretty-print JSON in a shell script?Extracting extension from filename in PythonHow to parse JSON in JavaWhy can't Python parse this JSON data?How can I pretty-print JSON using JavaScript?How to parse JSON using Node.js?How do I POST JSON data with Curl from a terminal/commandline to Test Spring REST?How do I write JSON data to a file?How to prettyprint a JSON file?

LWC SFDX source push error TypeError: LWC1009: decl.moveTo is not a function

How old can references or sources in a thesis be?

Why do I get two different answers for this counting problem?

Is it unprofessional to ask if a job posting on GlassDoor is real?

Was any UN Security Council vote triple-vetoed?

Replacing matching entries in one column of a file by another column from a different file

Why is consensus so controversial in Britain?

LaTeX: Why are digits allowed in environments, but forbidden in commands?

How can I make my BBEG immortal short of making them a Lich or Vampire?

Did Shadowfax go to Valinor?

What does it mean to describe someone as a butt steak?

Why doesn't Newton's third law mean a person bounces back to where they started when they hit the ground?

How to format long polynomial?

Do I have a twin with permutated remainders?

What would happen to a modern skyscraper if it rains micro blackholes?

How does one intimidate enemies without having the capacity for violence?

Convert two switches to a dual stack, and add outlet - possible here?

High voltage LED indicator 40-1000 VDC without additional power supply

What defenses are there against being summoned by the Gate spell?

Are the number of citations and number of published articles the most important criteria for a tenure promotion?

Why does Kotter return in Welcome Back Kotter?

Does an object always see its latest internal state irrespective of thread?

I'm flying to France today and my passport expires in less than 2 months

Can an x86 CPU running in real mode be considered to be basically an 8086 CPU?



How to extract specific fields recursively from json output?


How do I format a Microsoft JSON date?How can I pretty-print JSON in a shell script?Extracting extension from filename in PythonHow to parse JSON in JavaWhy can't Python parse this JSON data?How can I pretty-print JSON using JavaScript?How to parse JSON using Node.js?How do I POST JSON data with Curl from a terminal/commandline to Test Spring REST?How do I write JSON data to a file?How to prettyprint a JSON file?






.everyoneloves__top-leaderboard:empty,.everyoneloves__mid-leaderboard:empty,.everyoneloves__bot-mid-leaderboard:empty height:90px;width:728px;box-sizing:border-box;








-2















Below is the sample json document or json variable I have. I'm using python for extracting the required fields as mentioned int the output section.



Can someone help on how to do this?



json_variable = 

"server01":
"address":"server01:5454",
"options": ,
"state":"online"
,
"server02":
"address":"server02:5454",
"options": ,
"state":"online"
,
"server03":
"address":"server03:5454",
"options": ,
"state":"online"



for x in json_variable:
print(x["address"])

Error:
Traceback (most recent call last):
File "<string>", line 30, in <module>
File "<string>", line 18, in getServerStatus
TypeError: 'shell.Dict' object is not iterable


I can get the required output by hard coding the fields as below, but i would like to do it dynamically as the number of servers vary depending upon the system queried and json returned.



print(json_variable["server01"]["address"])
print(json_variable["server02"]["address"])
print(json_variable["server03"]["address"])


Required Output:



server01:5454 --> online 
server02:5454 --> online
server03:5454 --> online









share|improve this question
























  • To do this generically, you're going to have to at least hardcode the patterns to look for so the code has a clue as to what you're interested in retrieving. Not sure why you seem to think it needs to be done recursively, however.

    – martineau
    Mar 9 at 1:00






  • 2





    What have you tried so far?

    – Klaus D.
    Mar 9 at 1:00






  • 1





    for server in json_variable.values(): print(f"server['address'] --> server['status']")

    – Jab
    Mar 9 at 1:02












  • @KlausD. I added the code that I tried.

    – sqlcheckpoint
    Mar 9 at 1:17

















-2















Below is the sample json document or json variable I have. I'm using python for extracting the required fields as mentioned int the output section.



Can someone help on how to do this?



json_variable = 

"server01":
"address":"server01:5454",
"options": ,
"state":"online"
,
"server02":
"address":"server02:5454",
"options": ,
"state":"online"
,
"server03":
"address":"server03:5454",
"options": ,
"state":"online"



for x in json_variable:
print(x["address"])

Error:
Traceback (most recent call last):
File "<string>", line 30, in <module>
File "<string>", line 18, in getServerStatus
TypeError: 'shell.Dict' object is not iterable


I can get the required output by hard coding the fields as below, but i would like to do it dynamically as the number of servers vary depending upon the system queried and json returned.



print(json_variable["server01"]["address"])
print(json_variable["server02"]["address"])
print(json_variable["server03"]["address"])


Required Output:



server01:5454 --> online 
server02:5454 --> online
server03:5454 --> online









share|improve this question
























  • To do this generically, you're going to have to at least hardcode the patterns to look for so the code has a clue as to what you're interested in retrieving. Not sure why you seem to think it needs to be done recursively, however.

    – martineau
    Mar 9 at 1:00






  • 2





    What have you tried so far?

    – Klaus D.
    Mar 9 at 1:00






  • 1





    for server in json_variable.values(): print(f"server['address'] --> server['status']")

    – Jab
    Mar 9 at 1:02












  • @KlausD. I added the code that I tried.

    – sqlcheckpoint
    Mar 9 at 1:17













-2












-2








-2


1






Below is the sample json document or json variable I have. I'm using python for extracting the required fields as mentioned int the output section.



Can someone help on how to do this?



json_variable = 

"server01":
"address":"server01:5454",
"options": ,
"state":"online"
,
"server02":
"address":"server02:5454",
"options": ,
"state":"online"
,
"server03":
"address":"server03:5454",
"options": ,
"state":"online"



for x in json_variable:
print(x["address"])

Error:
Traceback (most recent call last):
File "<string>", line 30, in <module>
File "<string>", line 18, in getServerStatus
TypeError: 'shell.Dict' object is not iterable


I can get the required output by hard coding the fields as below, but i would like to do it dynamically as the number of servers vary depending upon the system queried and json returned.



print(json_variable["server01"]["address"])
print(json_variable["server02"]["address"])
print(json_variable["server03"]["address"])


Required Output:



server01:5454 --> online 
server02:5454 --> online
server03:5454 --> online









share|improve this question
















Below is the sample json document or json variable I have. I'm using python for extracting the required fields as mentioned int the output section.



Can someone help on how to do this?



json_variable = 

"server01":
"address":"server01:5454",
"options": ,
"state":"online"
,
"server02":
"address":"server02:5454",
"options": ,
"state":"online"
,
"server03":
"address":"server03:5454",
"options": ,
"state":"online"



for x in json_variable:
print(x["address"])

Error:
Traceback (most recent call last):
File "<string>", line 30, in <module>
File "<string>", line 18, in getServerStatus
TypeError: 'shell.Dict' object is not iterable


I can get the required output by hard coding the fields as below, but i would like to do it dynamically as the number of servers vary depending upon the system queried and json returned.



print(json_variable["server01"]["address"])
print(json_variable["server02"]["address"])
print(json_variable["server03"]["address"])


Required Output:



server01:5454 --> online 
server02:5454 --> online
server03:5454 --> online






python json python-2.7






share|improve this question















share|improve this question













share|improve this question




share|improve this question








edited Mar 9 at 4:18







sqlcheckpoint

















asked Mar 9 at 0:54









sqlcheckpointsqlcheckpoint

351520




351520












  • To do this generically, you're going to have to at least hardcode the patterns to look for so the code has a clue as to what you're interested in retrieving. Not sure why you seem to think it needs to be done recursively, however.

    – martineau
    Mar 9 at 1:00






  • 2





    What have you tried so far?

    – Klaus D.
    Mar 9 at 1:00






  • 1





    for server in json_variable.values(): print(f"server['address'] --> server['status']")

    – Jab
    Mar 9 at 1:02












  • @KlausD. I added the code that I tried.

    – sqlcheckpoint
    Mar 9 at 1:17

















  • To do this generically, you're going to have to at least hardcode the patterns to look for so the code has a clue as to what you're interested in retrieving. Not sure why you seem to think it needs to be done recursively, however.

    – martineau
    Mar 9 at 1:00






  • 2





    What have you tried so far?

    – Klaus D.
    Mar 9 at 1:00






  • 1





    for server in json_variable.values(): print(f"server['address'] --> server['status']")

    – Jab
    Mar 9 at 1:02












  • @KlausD. I added the code that I tried.

    – sqlcheckpoint
    Mar 9 at 1:17
















To do this generically, you're going to have to at least hardcode the patterns to look for so the code has a clue as to what you're interested in retrieving. Not sure why you seem to think it needs to be done recursively, however.

– martineau
Mar 9 at 1:00





To do this generically, you're going to have to at least hardcode the patterns to look for so the code has a clue as to what you're interested in retrieving. Not sure why you seem to think it needs to be done recursively, however.

– martineau
Mar 9 at 1:00




2




2





What have you tried so far?

– Klaus D.
Mar 9 at 1:00





What have you tried so far?

– Klaus D.
Mar 9 at 1:00




1




1





for server in json_variable.values(): print(f"server['address'] --> server['status']")

– Jab
Mar 9 at 1:02






for server in json_variable.values(): print(f"server['address'] --> server['status']")

– Jab
Mar 9 at 1:02














@KlausD. I added the code that I tried.

– sqlcheckpoint
Mar 9 at 1:17





@KlausD. I added the code that I tried.

– sqlcheckpoint
Mar 9 at 1:17












2 Answers
2






active

oldest

votes


















1














Here's another way to get the server status from the JSON.



json_info = 
"server01":
"address":"server01:5454",
"options": ,
"state":"online"
,
"server02":
"address":"server02:5454",
"options": ,
"state":"online"
,
"server03":
"address":"server03:5454",
"options": ,
"state":"online"



for server in json_info.values():
server_status = server['state']
if 'online' in server_status:
server_name = server.get('address')
print (' is online'.format(server_name.split(':')[0]))
# output
# server01 is online
# server02 is online
# server03 is online
#
# print (' --> online'.format(server_name))
# output
# server01:5454 --> online
# server02:5454 --> online
# server03:5454 --> online
else:
server_name = server.get('address')
print(' is offline'.format(server_name.split(':')[0]))





share|improve this answer
































    1














    Treat it as a dictionary:



    for k, v in sample.items():
    print(v['address'] + "-->" + v['state'])





    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%2f55072939%2fhow-to-extract-specific-fields-recursively-from-json-output%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









      1














      Here's another way to get the server status from the JSON.



      json_info = 
      "server01":
      "address":"server01:5454",
      "options": ,
      "state":"online"
      ,
      "server02":
      "address":"server02:5454",
      "options": ,
      "state":"online"
      ,
      "server03":
      "address":"server03:5454",
      "options": ,
      "state":"online"



      for server in json_info.values():
      server_status = server['state']
      if 'online' in server_status:
      server_name = server.get('address')
      print (' is online'.format(server_name.split(':')[0]))
      # output
      # server01 is online
      # server02 is online
      # server03 is online
      #
      # print (' --> online'.format(server_name))
      # output
      # server01:5454 --> online
      # server02:5454 --> online
      # server03:5454 --> online
      else:
      server_name = server.get('address')
      print(' is offline'.format(server_name.split(':')[0]))





      share|improve this answer





























        1














        Here's another way to get the server status from the JSON.



        json_info = 
        "server01":
        "address":"server01:5454",
        "options": ,
        "state":"online"
        ,
        "server02":
        "address":"server02:5454",
        "options": ,
        "state":"online"
        ,
        "server03":
        "address":"server03:5454",
        "options": ,
        "state":"online"



        for server in json_info.values():
        server_status = server['state']
        if 'online' in server_status:
        server_name = server.get('address')
        print (' is online'.format(server_name.split(':')[0]))
        # output
        # server01 is online
        # server02 is online
        # server03 is online
        #
        # print (' --> online'.format(server_name))
        # output
        # server01:5454 --> online
        # server02:5454 --> online
        # server03:5454 --> online
        else:
        server_name = server.get('address')
        print(' is offline'.format(server_name.split(':')[0]))





        share|improve this answer



























          1












          1








          1







          Here's another way to get the server status from the JSON.



          json_info = 
          "server01":
          "address":"server01:5454",
          "options": ,
          "state":"online"
          ,
          "server02":
          "address":"server02:5454",
          "options": ,
          "state":"online"
          ,
          "server03":
          "address":"server03:5454",
          "options": ,
          "state":"online"



          for server in json_info.values():
          server_status = server['state']
          if 'online' in server_status:
          server_name = server.get('address')
          print (' is online'.format(server_name.split(':')[0]))
          # output
          # server01 is online
          # server02 is online
          # server03 is online
          #
          # print (' --> online'.format(server_name))
          # output
          # server01:5454 --> online
          # server02:5454 --> online
          # server03:5454 --> online
          else:
          server_name = server.get('address')
          print(' is offline'.format(server_name.split(':')[0]))





          share|improve this answer















          Here's another way to get the server status from the JSON.



          json_info = 
          "server01":
          "address":"server01:5454",
          "options": ,
          "state":"online"
          ,
          "server02":
          "address":"server02:5454",
          "options": ,
          "state":"online"
          ,
          "server03":
          "address":"server03:5454",
          "options": ,
          "state":"online"



          for server in json_info.values():
          server_status = server['state']
          if 'online' in server_status:
          server_name = server.get('address')
          print (' is online'.format(server_name.split(':')[0]))
          # output
          # server01 is online
          # server02 is online
          # server03 is online
          #
          # print (' --> online'.format(server_name))
          # output
          # server01:5454 --> online
          # server02:5454 --> online
          # server03:5454 --> online
          else:
          server_name = server.get('address')
          print(' is offline'.format(server_name.split(':')[0]))






          share|improve this answer














          share|improve this answer



          share|improve this answer








          edited Mar 9 at 2:44

























          answered Mar 9 at 2:14









          Life is complexLife is complex

          731518




          731518























              1














              Treat it as a dictionary:



              for k, v in sample.items():
              print(v['address'] + "-->" + v['state'])





              share|improve this answer



























                1














                Treat it as a dictionary:



                for k, v in sample.items():
                print(v['address'] + "-->" + v['state'])





                share|improve this answer

























                  1












                  1








                  1







                  Treat it as a dictionary:



                  for k, v in sample.items():
                  print(v['address'] + "-->" + v['state'])





                  share|improve this answer













                  Treat it as a dictionary:



                  for k, v in sample.items():
                  print(v['address'] + "-->" + v['state'])






                  share|improve this answer












                  share|improve this answer



                  share|improve this answer










                  answered Mar 9 at 2:05









                  S. WangS. Wang

                  112




                  112



























                      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%2f55072939%2fhow-to-extract-specific-fields-recursively-from-json-output%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

                      Thal And Out Agency railway station See also References External links Navigation menuOfficial Web Site of Pakistan RailwaysArchivedOfficial Web Site of Pakistan Railwayseeexpanding ite

                      Understanding generators in Python2019 Community Moderator ElectionGenerator function not working pythonFor loop not executing two timesGenerators - Printing generated valuesWhy can a python generator only be used once?What exactly do generators do?What does the “yield” keyword do?What does “list comprehension” mean? How does it work and how can I use it?sklearn Kfold acces single fold instead of for loopIs a generator the callable? Which is the generator?Apply Border To Range Of Cells Using OpenpyxlCalling an external command in PythonWhat are metaclasses in Python?What is the difference between @staticmethod and @classmethod?Finding the index of an item given a list containing it in PythonDifference between append vs. extend list methods in PythonHow can I safely create a nested directory in Python?Does Python have a ternary conditional operator?Understanding slice notationUnderstanding Python super() with __init__() methodsDoes Python have a string 'contains' substring method?

                      How can I change the color of pagination dots of UIPageControl?How to change UIPageControl dotsIs there a way to change page indicator dots colorCustomize dot with image of UIPageControl at index 0 of UIPageControlNo visible @interface for 'NSObject<PageControlDelegate>' declares the selector 'pageControlPageDidChange:'How to change the color of pagination dots in UIPageControl with a different color per pagepagecontrol indicator custom image instead of DefaultChanging the colour of UIPageControl dots in MonoTouchpagecontrol selectable page visibility color?Alternative way to load ViewControllers on a UIPageControlHow to set only layer.border-color for UIpage control dots in swiftHow can I develop for iPhone using a Windows development machine?How to change the name of an iOS app?UITableView - change section header coloruipagecontrol indicator(dot)issueCustom UIPageControl dots color not changingchange the interspace between UIPageControl dotsHow to change Status Bar text color in iOSHow can I change image tintColor in iOS and WatchKitUIPageControl dots with larger space in between each dotsHow to change the color of pagination dots in UIPageControl with a different color per page