如何使用python flask 读取json字符串

hfyxw5xn  于 2022-11-26  发布在  Python
关注(0)|答案(1)|浏览(134)

如何使用pytohn模块读取/过滤“webserver 1”那个字符串

{
          "Title":"Nginx Service"
          "Instant":"[
           {\"Hostname\":\"webserver1\"}
          ]"
}


          "Title":"Nginx Service"

          "Instant":"[

           {\"Hostname\":\"webserver1\"}

          ]"

}


data = json.load(jsonfile)

return (data)
xoefb8l8

xoefb8l81#

响应取决于inut json文件,这在你的帖子中并不清楚,因为你还没有写一个正确的json。

选项1:json文件是一个字典

假设我们有这个json文件作为输入,名为myjsonfile_dict.json

{
    "Title": "Nginx Service",
    "Instant": [{
        "Hostname": "webserver1"
    }]
}

我们可以像这样得到'Hostname'的值(即'webserver1'):

import sys

# Reading the json file
try:
    with open("myjsonfile_dict.json", "r") as read_content:
        dict_data_from_file: dict = json.load(read_content)
except (FileNotFoundError, PermissionError, OSError, ValueError) as e:
    print(f"Error opening the file: {e}")
    sys.exit()

# Parsing the read dictionary
try:
    # Option 1.a: Get variable if only one item in the "Instant" list
    hostname: str = dict_data_from_file['Instant'][0]['Hostname']
    print(f'The first hostname is {hostname}')

    # Option 1.b: Get variable with multiple items in the "Instant" list
    hostnames: list = []
    for instant_list in dict_data_from_file['Instant']:
        hostnames.append(instant_list['Hostname'])
    print('All the hostnames are:')
    print(*hostnames, sep=", ")

except (KeyError, TypeError) as e:
    print(f"Error parsing the json file: {e}")

选项2:json文件是字典列表

给定此json文件作为输入,名为myjsonfile_list_of_dicts.json

[
    {
        "Title": "Nginx Service",
        "Instant": [{
            "Hostname": "webserver1"
        }]
    },
    {
        "Title": "Nginx Service",
        "Instant": [{
            "Hostname": "webserver2"
        }]
    }
]

我们可以像下面这样获取“Hostname”的值(即“webserver1”和“webserver2”):

import sys

# Reading the json file
try:
    with open("myjsonfile_list_of_dicts.json", "r") as read_content:
        list_data_from_file: dict = json.load(read_content)
except (FileNotFoundError, PermissionError, OSError, ValueError) as e:
    print(f"Error opening the file: {e}")
    sys.exit()

# Parsing the read list of dictionaries
try:
    # Option 2.a: Get variable with multiple items in the "Instant" list
    hostnames_a: list = []
    for item in list_data_from_file:
        hostnames_a.append(dict_data_from_file['Instant'][0]['Hostname'])
    print('All the hostnames are:')
    print(*hostnames_a, sep=", ")

    # Option 2.b: Get variable with multiple items in the "Instant" list
    hostnames: list = []
    for item in list_data_from_file:
        for instant_list in item['Instant']:
            hostnames.append(instant_list['Hostname'])
    print('All the hostnames are:')
    print(*hostnames, sep=", ")

except (KeyError, TypeError) as e:
    print(f"Error parsing the json file: {e}")

建议:

相关问题