简体   繁体   中英

Json in python 3 get element

I build this json file

{
    "systems-under-test": [{
            "type": "url",
            "sytems": [
                "www.google.com",
                "www.google.com",
                "www.google.com"
            ]
        },
        {
            "type": "api",
            "sytems": [
                "api.com",
                "api.fr"
            ]
        },
        {
            "type": "ip",
            "sytems": [
                "172.168 .1 .1",
                "172.168 .1 .0"
            ]
        }
    ],
    "headers-default-configuration": {
        "boolean": false
    },
    "headers-custom-configuration": {
        "boolean": true,
        "settings": {
            "headers": {
                "header-name": "x - frame - options",
                "expected-value": ["deny", "sameorigin"]
            }
        }
    },
    "header-results": []
}

I want to add system under test to 3 different list, based on the type, for example type = URL to url_list and so on.

    def loadConfigFile(self, urls_list=None):
        path = self.validate_path()
        with open(path) as f:
            data = json.load(f)
        pprint(data)
        for key, value in data.items():
            if key == "systems-under-test":
                for x in value:
                    print(x.keys()[0])
                    if x.values[0] == "url":
                        url = x.get("systems")
                        print(url)
                        urls_list.add[url]

the output needs to be like:

all this : 
"www.google.com"
"www.google.com"
"www.google.com"

needs to be added to url_list

when I try to access key value by using : x.values[0] == "URL", I keep getting this error

TypeError: 'dict_keys' object does not support indexing

the problem is solved by adding () as shown bellow:

    def loadConfigFile(self, urls_list=None):
        path = self.validate_path()
        with open(path) as f:
            data = json.load(f)
        pprint(data)
        for key, value in data.items():
            if key == "systems-under-test":
                for x in value:
                    if list(x.values())[0] == "url":
                        urls = list(x.values())[1]
                        for url in urls:
                            print(url)

results will be

www.google.com
www.google.com
www.google.com

This seems like an easy way to do it:

from json import load

with open("data.json") as json_file:
    data = load(json_file)
    test_data = data["systems-under-test"][0]
    if test_data["type"] == "url":
        print(test_data["sytems"])

Output:

['www.google.com', 'www.google.com', 'www.google.com']

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