简体   繁体   中英

How to access different portions of a json data-structure?

{
"commands" : [
           {"command" : [
                         {"name" : "Base ls Command","shell" : "ls"},
                         {"name" : "Advanced ls command" : "shell" : "ls -la"}
              ]
           },
          {"command":[
                             {"name" :"Base netstat command", "shell" : "netstat"},
                             {"name" : "Advanced netstat command" : "shell" : "netstat -tunalp | grep LISTEN | grep nginx"}
             ]
          }
 ]
}

So, that I can access it as follows:

for cmd in file[commands][command]:
    'name' = cmd['name']
    shell = cmd['shell']

But, I am getting invalid syntax error.

You should use the json module to load the file correctly.

import json

command = json.load(open('file_name.json'))

name = command['commands']['command']['name']

you can read more about the module in the documents: https://docs.python.org/2/library/json.html

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM